package com.lancoo.cvas.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.cvas.entity.*;
import com.lancoo.cvas.exception.BizException;
import com.lancoo.cvas.mapper.*;
import com.lancoo.cvas.pojo.common.*;
import com.lancoo.cvas.pojo.constant.GlobalConstant;
import com.lancoo.cvas.pojo.dto.*;
import com.lancoo.cvas.pojo.excel.ErrorExcelVo;
import com.lancoo.cvas.pojo.excel.ExcelTeachingClassDto;
import com.lancoo.cvas.pojo.excel.ExcelTeachingDto;
import com.lancoo.cvas.pojo.excel.ReleaseSelectionToExcel;
import com.lancoo.cvas.pojo.response.basicPlatform.BaseGrade;
import com.lancoo.cvas.pojo.vo.*;
import com.lancoo.cvas.service.*;
import com.lancoo.cvas.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.AnnotatedArrayType;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

@Slf4j
@Service("teachingClassService")
public class TeachingClassServiceImpl extends ServiceImpl<TeachingClassMapper, TeachingClass> implements TeachingClassService {

    @Resource
    private TeachingClassMapper teachingClassMapper;

    @Resource
    private PlanTeachingMapper planTeachingMapper;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private PlanTeachingCourseSegmentMapper planTeachingCourseSegmentMapper;

    @Resource
    private ClassInfoMapper classInfoMapper;

    @Resource
    private CourseService courseService;

    @Resource
    private TeachingClassWeekService teachingClassWeekService;

    @Resource
    private TeachingClassTeacherService teachingClassTeacherService;

    @Resource
    private SegmentMapper segmentMapper;

    @Resource
    private TeachingClassWeekMapper teachingClassWeekMapper;

    @Resource
    private MajorMapper majorMapper;

    @Resource
    private AssessmentMethodMapper assessmentMethodMapper;

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private TeachingClassTeacherMapper teachingClassTeacherMapper;

    @Resource
    private RoomMapper roomMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private TeacherService teacherService;

    @Resource
    private TeachingClassService teachingClassService;
    @Resource
    private ScheduleMapper scheduleMapper;
    @Resource
    private ScheduleConflictInfoService scheduleConflictInfoService;

    @Autowired
    private HttpServletRequest request;

    @Resource
    @Lazy
    private YunService yunService;

    @Resource
    private StudentRetakeService studentRetakeService;

    @Resource
    private TeachingClassStudentMapper teachingClassStudentMapper;
    @Resource
    private StudentService studentService;
    @Resource
    private TeachingClassStudentService teachingClassStudentService;
    @Resource
    private TaskToGradeService taskToGradeService;
    @Resource
    private ClassCourseCloseService classCourseCloseService;
    @Resource
    private SegmentService segmentService;

    @Resource
    private PlanTeachingStudentMapper planTeachingStudentMapper;

    @Resource
    private PlanTeachingService planTeachingService;

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private TaskInfoService taskInfoService;
    @Resource
    private RoomService roomService;
    @Resource
    private ParameterSettingService parameterSettingService;
    @Resource
    private ParameterSettingMapper parameterSettingMapper;
    @Resource
    private RuleCourseService ruleCourseService;
    @Resource
    private RuleClassProhibitService ruleClassProhibitService;
    @Resource
    private RuleCourseProhibitMajorService ruleCourseProhibitMajorService;
    @Resource
    private RuleTeachingClassProhibitService ruleTeachingClassProhibitService;
    @Resource
    private ScheduleService scheduleService;
    @Resource
    private AssessmentMethodService assessmentMethodService;
    @Resource
    private TaskToGradeMapper taskToGradeMapper;


    @Override
    public Integer deletedByClassInfos(Integer taskId) {

        return teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>().eq(TeachingClass::getTaskId, taskId)
                .set(TeachingClass::getDeleted, Deleted.YES));
    }

    @Override
    public Integer addBatch(Integer taskId, List<ClassInfoVo> classInfoVos) {
        List<TeachingClass> teachingClasses = new ArrayList<>();
        List<PlanTeaching> planTeachings = planTeachingMapper.selectList(new LambdaQueryWrapper<PlanTeaching>()
                .eq(PlanTeaching::getTaskId, taskId).eq(PlanTeaching::getDeleted, Deleted.NOT));


        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentMapper.selectList(
                new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                        .eq(PlanTeachingCourseSegment::getTaskId, taskId).eq(PlanTeachingCourseSegment::getDeleted, Deleted.NOT));

        List<ClassInfo> classInfos = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId));


        for (int i = 0; i < classInfoVos.size(); i++) {
            int finalI = i;
            PlanTeaching teacherPlanId = planTeachings.stream()
                    .filter(p -> classInfoVos.get(finalI).getGradeId().equals(p.getGradeId()) && classInfoVos.get(finalI).getMajorId()
                            .equals(p.getBaseMajorId())).findFirst().orElse(null);

            List<PlanTeachingCourseSegment> pT = planTeachingCourseSegments.stream().filter(p -> p.getBaseTeachingPlanId()
                    .equals(teacherPlanId.getBaseTeachingPlanId()))
                    .collect(Collectors.toList());

            List<String> courses = pT.stream().filter(p -> p.getFlag().equals(1)).map(PlanTeachingCourseSegment::getBaseCourseId)
                    .distinct().collect(Collectors.toList());

            List<String> segments = pT.stream().filter(p -> p.getFlag().equals(2)).map(PlanTeachingCourseSegment::getBaseCourseId)
                    .distinct().collect(Collectors.toList());

            ClassInfo classInfo = classInfos.stream().filter(p -> p.getClassId()
                    .equals(classInfoVos.get(finalI).getClassId())).findFirst().orElse(null);


            if (CollUtil.isNotEmpty(courses)) {
                for (String cours : courses) {

                    TeachingClass teachingClass = new TeachingClass();
                    teachingClass.setTaskId(taskId);
                    teachingClass.setClassId(classInfoVos.get(i).getClassId());
                    teachingClass.setTeachingClassName(classInfoVos.get(i).getClassName() + "课程" + "(" + i + ")班");

                    teachingClass.setCourseId(Long.valueOf(cours));
                    if (classInfo != null) {
                        teachingClass.setClassNum(classInfo.getStudentNumber());
                    }
                    teachingClass.setGradeId(classInfoVos.get(i).getGradeId());
                    teachingClass.setTeachingClassType(0);
                    teachingClass.setFlag(1);
                    teachingClass.setCampusId(classInfoVos.get(i).getCampusId());
                    teachingClass.setCampusName(classInfoVos.get(i).getCampusName());
                    teachingClass.setIsEnable(1);
                    teachingClasses.add(teachingClass);
                }

            }


            if (CollUtil.isNotEmpty(segments)) {
                for (String segmentName : segments) {

                    TeachingClass teachingClass = new TeachingClass();
                    teachingClass.setTaskId(taskId);
                    teachingClass.setClassId(classInfoVos.get(i).getClassId());
                    teachingClass.setTeachingClassName(classInfoVos.get(i).getClassName() + "环节" + "(" + i + ")班");

                    teachingClass.setCourseId(Long.valueOf(segmentName));
                    if (classInfo != null) {
                        teachingClass.setClassNum(classInfo.getStudentNumber());
                    }
                    teachingClass.setGradeId(classInfoVos.get(i).getGradeId());
                    teachingClass.setTeachingClassType(0);
                    teachingClass.setFlag(2);
                    teachingClass.setCampusId(classInfoVos.get(i).getCampusId());
                    teachingClass.setCampusName(classInfoVos.get(i).getCampusName());
                    teachingClass.setIsEnable(1);
                    teachingClasses.add(teachingClass);
                }

            }
        }

        return teachingClassMapper.saveBatch(teachingClasses);
    }

    @Override
    public Integer addBatchByMajor(Integer taskId, List<GradeVo> gradeInfoVos) {
        List<TeachingClass> teachingClasses = new ArrayList<>();
        List<PlanTeaching> planTeachings = planTeachingMapper.selectList(new LambdaQueryWrapper<PlanTeaching>()
                .eq(PlanTeaching::getTaskId, taskId).eq(PlanTeaching::getDeleted, Deleted.NOT));


        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentMapper.selectList(
                new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                        .eq(PlanTeachingCourseSegment::getTaskId, taskId).eq(PlanTeachingCourseSegment::getDeleted, Deleted.NOT));

        List<ClassInfo> classInfos = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId));

        for (int i = 0; i < gradeInfoVos.size(); i++) {

            List<MajorVo> majorVos = gradeInfoVos.get(i).getFacultyMajorInfoList();

            for (int j = 0; j < majorVos.size(); j++) {

                int finalI = i;
                int finalJ = j;
                PlanTeaching teacherPlanId = planTeachings.stream()
                        .filter(p -> gradeInfoVos.get(finalI).getGradeId().equals(p.getGradeId()) && majorVos.get(finalJ).getMajorId()
                                .equals(p.getBaseMajorId())).findFirst().orElse(null);

                List<PlanTeachingCourseSegment> pT = planTeachingCourseSegments.stream().filter(p -> p.getBaseTeachingPlanId()
                        .equals(teacherPlanId.getBaseTeachingPlanId()))
                        .collect(Collectors.toList());

                List<String> courses = pT.stream().filter(p -> p.getFlag().equals(1)).map(PlanTeachingCourseSegment::getBaseCourseId)
                        .distinct().collect(Collectors.toList());

                List<String> segments = pT.stream().filter(p -> p.getFlag().equals(2)).map(PlanTeachingCourseSegment::getBaseCourseId)
                        .distinct().collect(Collectors.toList());

                List<ClassInfo> classInfo = classInfos.stream().filter(p -> p.getGradeId()
                        .equals(gradeInfoVos.get(finalI).getGradeId()) && p.getMajorId().equals(majorVos.get(finalJ).getMajorId()))
                        .collect(Collectors.toList());

                classInfo.forEach(o -> {
                    if (CollUtil.isNotEmpty(courses)) {
                        for (String cours : courses) {

                            TeachingClass teachingClass = new TeachingClass();
                            teachingClass.setTaskId(taskId);
                            teachingClass.setClassId(o.getClassId());
                            teachingClass.setTeachingClassName(o.getClassName() + "课程" + "(" + finalI + ")班");

                            teachingClass.setCourseId(Long.valueOf(cours));

                            teachingClass.setClassNum(o.getStudentNumber());

                            teachingClass.setGradeId(gradeInfoVos.get(finalI).getGradeId());
                            teachingClass.setTeachingClassType(0);
                            teachingClass.setFlag(1);
                            teachingClass.setCampusId(o.getCampusId());
                            teachingClass.setCampusName(o.getCampusName());
                            teachingClass.setIsEnable(1);
                            teachingClasses.add(teachingClass);
                        }

                    }


                    if (CollUtil.isNotEmpty(segments)) {
                        for (String segmentName : segments) {

                            TeachingClass teachingClass = new TeachingClass();
                            teachingClass.setTaskId(taskId);
                            teachingClass.setClassId(o.getClassId());
                            teachingClass.setTeachingClassName(o.getClassName() + "环节" + "(" + finalI + ")班");

                            teachingClass.setCourseId(Long.valueOf(segmentName));
                            teachingClass.setClassNum(o.getStudentNumber());

                            teachingClass.setGradeId(gradeInfoVos.get(finalJ).getGradeId());
                            teachingClass.setTeachingClassType(0);
                            teachingClass.setFlag(2);
                            teachingClass.setCampusId(o.getCampusId());
                            teachingClass.setCampusName(o.getCampusName());
                            teachingClass.setIsEnable(1);
                            teachingClasses.add(teachingClass);
                        }
                    }
                });
            }
        }
        return teachingClassMapper.saveBatch(teachingClasses);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addBatchTeachingClass(Integer taskId, Boolean isUpdate) {


        List<TeachingClass> teachingClassList1 = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).list();

        if (CollUtil.isNotEmpty(teachingClassList1)) {

            List<Long> teachingClassIds = teachingClassList1.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());

            teachingClassWeekMapper.delete(new LambdaQueryWrapper<TeachingClassWeek>().in(TeachingClassWeek::getTeachingClassId, teachingClassIds));
            teachingClassStudentMapper.delete(new LambdaQueryWrapper<TeachingClassStudent>().in(TeachingClassStudent::getTeachingClassId, teachingClassIds));
            teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>().in(TeachingClassTeacher::getTeachingClassId, teachingClassIds));
            teachingClassMapper.delete(new LambdaQueryWrapper<TeachingClass>().eq(TeachingClass::getTaskId, taskId).in(TeachingClass::getTeachingClassId, teachingClassIds));
            parameterSettingMapper.delete(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId));
            ruleCourseService.lambdaUpdate().eq(RuleCourse::getTaskId, taskId).remove();
            ruleClassProhibitService.lambdaUpdate().eq(RuleClassProhibit::getTaskId, taskId).remove();
            ruleCourseProhibitMajorService.lambdaUpdate().eq(RuleCourseProhibitMajor::getTaskId, taskId).remove();
            ruleTeachingClassProhibitService.lambdaUpdate().eq(RuleTeachingClassProhibit::getTaskId, taskId).remove();
            scheduleService.lambdaUpdate().eq(Schedule::getTaskId, taskId).remove();
            scheduleConflictInfoService.lambdaUpdate().eq(ScheduleConflictInfo::getTaskId, taskId).remove();
        }


        List<TeachingClass> teachingClasses = new ArrayList<>();
        List<TeachingClassWeek> teachingClassWeeks = new ArrayList<>();
        List<TaskToGrade> taskToGradeList = taskToGradeService.lambdaQuery().eq(TaskToGrade::getTaskId, taskId)
                .eq(TaskToGrade::getDeleted, Deleted.NOT.getCode()).list();

        List<String> gradeIds = taskToGradeList.stream().map(TaskToGrade::getGradeId).collect(Collectors.toList());


        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId));

        TaskInfo taskInfo = taskInfoService.getById(taskId);

        List<Room> roomList = roomService.lambdaQuery().eq(Room::getSchoolId, taskInfo.getSchoolId())
                .eq(Room::getTerm, taskInfo.getTerm())
                .eq(Room::getDeleted, Deleted.NOT.getCode()).list();


        List<CourseByClassDTO> courseByClassDTOList = new ArrayList<>();
        List<SegmentByClassDTO> segmentByClassDTOList = new ArrayList<>();

        List<AssessmentMethod> assessmentMethodList = assessmentMethodMapper.selectList(new LambdaQueryWrapper<AssessmentMethod>().eq(AssessmentMethod::getSchoolId, taskInfo.getSchoolId()));

        AssessmentMethod assessmentMethod = assessmentMethodList.stream().filter(p -> "考试".equals(p.getAssessmentName())).findFirst().orElse(null);


        gradeIds.forEach(o -> {

            List<ClassInfo> classInfos = classInfoList.stream().filter(p -> p.getGradeId().equals(o)).collect(Collectors.toList());
            classInfos.forEach(c -> {
                List<CourseByClassDTO> courseListByClass = getCourseListByClass(taskId, c.getClassId());
                courseListByClass.forEach(cbc -> {
                    cbc.setClassId(c.getId());
                });
                courseByClassDTOList.addAll(courseListByClass);
                courseListByClass.forEach(cs -> {
                    TeachingClass teachingClass = new TeachingClass();
                    teachingClass.setTaskId(taskId);
                    teachingClass.setClassId(String.valueOf(c.getId()));
                    teachingClass.setClassName(c.getClassName());
                    teachingClass.setTeachingClassName(c.getClassName() + cs.getCourseName());
                    teachingClass.setCourseId(cs.getCourseId());
                    teachingClass.setCourseName(cs.getCourseName());
                    teachingClass.setClassNum(CollUtil.isNotEmpty(cs.getBaseStudentId()) ? cs.getBaseStudentId().size() : 0);
                    teachingClass.setGradeId(c.getGradeId());
                    teachingClass.setReserve(cs.getBaseTeachingPlanId());
                    teachingClass.setGradeName(c.getGradeName());
                    teachingClass.setTeachingClassType(0);
                    teachingClass.setFlag(1);
                    teachingClass.setCampusId(c.getCampusId());
                    teachingClass.setCampusName(c.getCampusName());
                    teachingClass.setIsEnable(0);
                    teachingClass.setDeleted(Deleted.NOT.getCode());
                    teachingClasses.add(teachingClass);
                });

                List<SegmentByClassDTO> segmentListByClass = getSegmentListByClass(taskId, c.getClassId());
                segmentListByClass.forEach(sbc -> {
                    sbc.setClassId(c.getId());
                });

                segmentByClassDTOList.addAll(segmentListByClass);
                segmentListByClass.forEach(sc -> {
                    TeachingClass teachingClass = new TeachingClass();
                    teachingClass.setTaskId(taskId);
                    teachingClass.setClassId(String.valueOf(c.getId()));
                    teachingClass.setClassName(c.getClassName());
                    teachingClass.setTeachingClassName(c.getClassName() + sc.getSegmentName());
                    teachingClass.setCourseId(sc.getSegmentId());
                    teachingClass.setCourseName(sc.getSegmentName());
                    teachingClass.setClassNum(CollUtil.isNotEmpty(sc.getBaseStudentId()) ? sc.getBaseStudentId().size() : 0);
                    teachingClass.setGradeId(c.getGradeId());
                    teachingClass.setGradeName(c.getGradeName());
                    teachingClass.setReserve(sc.getBaseTeachingPlanId());
                    teachingClass.setTeachingClassType(0);
                    teachingClass.setFlag(2);
                    teachingClass.setCampusId(c.getCampusId());
                    teachingClass.setCampusName(c.getCampusName());
                    teachingClass.setIsEnable(0);
                    teachingClass.setDeleted(Deleted.NOT.getCode());
                    teachingClasses.add(teachingClass);
                });

            });
        });


        teachingClassService.saveBatch(teachingClasses);

        List<Course> courseList = courseMapper.getCourseList(taskId);


        WeekDateVo weekDateVo = taskInfoService.countWeek(taskId);
        long weekCount = weekDateVo.getWeekCount();
        String result = LongStream.range(0, weekCount).mapToObj(i -> "1").reduce((s1, s2) -> s1 + s2).orElse("");


        for (TeachingClass teachingClass : teachingClasses) {

            Course course = courseList.stream().filter(p -> p.getCourseId().equals(teachingClass.getCourseId())).findFirst().orElse(null);
            ClassInfo classInfo = classInfoList.stream().filter(p -> p.getId().equals(Long.valueOf(teachingClass.getClassId()))).findFirst().orElse(null);
            List<Room> room = new ArrayList<>();
            if (ObjUtil.isNotNull(classInfo.getRoomId())) {
                room = roomList.stream().filter(p -> p.getRoomId().equals(classInfo.getRoomId())).collect(Collectors.toList());
            }

            if (teachingClass.getFlag() == 1) {

                if (ObjUtil.isNull(course.getLectureHour())) {

                    TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                    teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                    if (CollUtil.isNotEmpty(room)) {
                        Room room1 = room.get(0);
                        teachingClassWeek.setRoomId(room1.getRoomId());
                        teachingClassWeek.setRoomType(room1.getRoomType());
                        teachingClass.setRoomId(room1.getRoomId());
                    }

                    teachingClassWeek.setAssessmentId(assessmentMethod.getAssessmentId());
                    teachingClassWeek.setAssessmentName(assessmentMethod.getAssessmentName());

                    teachingClassWeek.setSign(0);
                    teachingClassWeek.setHourType(1);
                    teachingClassWeek.setWeek(result);
                    teachingClassWeek.setStartWeek(1);
                    teachingClassWeek.setEndWeek((int) weekCount);
                    teachingClassWeek.setWeekNum(1);
                    teachingClassWeek.setConnectNumber(1);
                    teachingClassWeek.setConnectSection(1);
                    teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                    teachingClassWeeks.add(teachingClassWeek);

                }


                if (course.getLectureHour() != null) {
                    TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                    teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                    if (CollUtil.isNotEmpty(room)) {
                        Room room1 = room.get(0);
                        teachingClassWeek.setRoomId(room1.getRoomId());
                        teachingClassWeek.setRoomType(room1.getRoomType());
                        teachingClass.setRoomId(room1.getRoomId());
                    }

                    teachingClassWeek.setAssessmentId(assessmentMethod.getAssessmentId());
                    teachingClassWeek.setAssessmentName(assessmentMethod.getAssessmentName());

                    teachingClassWeek.setSign(0);
                    teachingClassWeek.setHourType(1);
                    teachingClassWeek.setWeek(result);
                    teachingClassWeek.setStartWeek(1);
                    teachingClassWeek.setEndWeek((int) weekCount);
                    teachingClassWeek.setWeekNum((int) (course.getLectureHour() / weekCount) == 0 ? 1 : (int) (course.getLectureHour() / weekCount));
                    teachingClassWeek.setConnectNumber(1);
                    teachingClassWeek.setConnectSection(1);
                    teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                    teachingClassWeeks.add(teachingClassWeek);
                }

                if (course.getExperimentalHour() != null && course.getExperimentalHour() > 0) {
                    TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                    teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                    if (CollUtil.isNotEmpty(room)) {
                        Room room1 = room.get(0);
                        teachingClassWeek.setRoomId(room1.getRoomId());
                        teachingClassWeek.setRoomType(room1.getRoomType());
                        teachingClass.setRoomId(room1.getRoomId());
                    }

                    teachingClassWeek.setSign(0);
                    teachingClassWeek.setAssessmentId(assessmentMethod.getAssessmentId());
                    teachingClassWeek.setAssessmentName(assessmentMethod.getAssessmentName());
                    teachingClassWeek.setHourType(2);
                    teachingClassWeek.setWeek(result);
                    teachingClassWeek.setStartWeek(1);
                    teachingClassWeek.setEndWeek((int) weekCount);
                    teachingClassWeek.setConnectNumber(1);
                    teachingClassWeek.setConnectSection(1);
                    teachingClassWeek.setWeekNum((int) (course.getExperimentalHour() / weekCount));
                    teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                    teachingClassWeeks.add(teachingClassWeek);
                }
                if (course.getComputerHour() != null && course.getComputerHour() > 0) {
                    TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                    if (CollUtil.isNotEmpty(room)) {
                        Room room1 = room.get(0);
                        teachingClassWeek.setRoomId(room1.getRoomId());
                        teachingClassWeek.setRoomType(room1.getRoomType());
                        teachingClass.setRoomId(room1.getRoomId());
                    }

                    teachingClassWeek.setAssessmentId(assessmentMethod.getAssessmentId());
                    teachingClassWeek.setAssessmentName(assessmentMethod.getAssessmentName());
                    teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                    teachingClassWeek.setHourType(3);
                    teachingClassWeek.setWeek(result);
                    teachingClassWeek.setSign(0);
                    teachingClassWeek.setStartWeek(1);
                    teachingClassWeek.setEndWeek((int) weekCount);
                    teachingClassWeek.setConnectNumber(1);
                    teachingClassWeek.setConnectSection(1);
                    teachingClassWeek.setWeekNum((int) (course.getComputerHour() / weekCount));
                    teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                    teachingClassWeeks.add(teachingClassWeek);
                }
                if (course.getOtherHour() != null && course.getOtherHour() > 0) {
                    TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                    if (CollUtil.isNotEmpty(room)) {
                        Room room1 = room.get(0);
                        teachingClassWeek.setRoomId(room1.getRoomId());
                        teachingClassWeek.setRoomType(room1.getRoomType());
                        teachingClass.setRoomId(room1.getRoomId());
                    }

                    teachingClassWeek.setSign(0);
                    teachingClassWeek.setStartWeek(1);
                    teachingClassWeek.setEndWeek((int) weekCount);
                    teachingClassWeek.setAssessmentId(assessmentMethod.getAssessmentId());
                    teachingClassWeek.setAssessmentName(assessmentMethod.getAssessmentName());
                    teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                    teachingClassWeek.setHourType(4);
                    teachingClassWeek.setWeek(result);
                    teachingClassWeek.setConnectNumber(1);
                    teachingClassWeek.setConnectSection(1);
                    teachingClassWeek.setWeekNum((int) (course.getOtherHour() / weekCount));
                    teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                    teachingClassWeeks.add(teachingClassWeek);
                }

            } else if (teachingClass.getFlag() == 2) {
                TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                teachingClassWeek.setHourType(0);
                teachingClassWeek.setStartWeek(1);
                teachingClassWeek.setEndWeek((int) weekCount);
                teachingClassWeek.setSign(0);
                teachingClassWeek.setWeek(result);
                teachingClassWeeks.add(teachingClassWeek);
            }
        }

        teachingClassService.saveOrUpdateBatch(teachingClasses);

        Consumer<List<TeachingClassWeek>> studentConsumer = o -> teachingClassWeekMapper.addBatch(o);
        BatchInsert.batchSplitInsert(teachingClassWeeks, studentConsumer);


        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


        List<TeachingClassStudent> teachingClassStudentList = new ArrayList<>();

        List<Student> studentList = studentService.lambdaQuery().eq(Student::getTaskId, taskId).eq(Student::getDeleted, Deleted.NOT.getCode()).list();

        teachingClassList.forEach(o -> {
            List<CourseByClassDTO> courseByClassDTO = courseByClassDTOList.stream().filter(p -> String.valueOf(p.getClassId()).equals(o.getClassId()) && p.getCourseId().equals(o.getCourseId()) && o.getFlag() == 1).collect(Collectors.toList());

            List<SegmentByClassDTO> segmentByClassDTO = segmentByClassDTOList.stream().filter(p -> String.valueOf(p.getClassId()).equals(o.getClassId()) && p.getSegmentId().equals(o.getCourseId()) && o.getFlag() == 2).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(courseByClassDTO)) {
                courseByClassDTO.forEach(cto -> {
                    List<String> baseStudentIds = cto.getBaseStudentId();
                    List<Student> students = studentList.stream().filter(p -> baseStudentIds.stream().anyMatch(bs -> p.getBaseStudentId().equals(bs)))
                            .collect(Collectors.toList());
                    students.forEach(s -> {
                        TeachingClassStudent teachingClassStudent = new TeachingClassStudent();
                        teachingClassStudent.setTeachingClassId(o.getTeachingClassId());
                        teachingClassStudent.setStudentId(s.getStudentId());
                        teachingClassStudent.setFlag(1);
                        teachingClassStudent.setDeleted(Deleted.NOT.getCode());
                        teachingClassStudentList.add(teachingClassStudent);
                    });
                });
            }


            if (CollUtil.isNotEmpty(segmentByClassDTO)) {
                segmentByClassDTO.forEach(sto -> {
                    List<String> baseStudentIds = sto.getBaseStudentId();
                    List<Student> students = studentList.stream().filter(p -> baseStudentIds.stream().anyMatch(bs -> p.getBaseStudentId().equals(bs)))
                            .collect(Collectors.toList());
                    students.forEach(s -> {
                        TeachingClassStudent teachingClassStudent = new TeachingClassStudent();
                        teachingClassStudent.setTeachingClassId(o.getTeachingClassId());
                        teachingClassStudent.setStudentId(s.getStudentId());
                        teachingClassStudent.setFlag(1);
                        teachingClassStudent.setDeleted(Deleted.NOT.getCode());
                        teachingClassStudentList.add(teachingClassStudent);
                    });
                });
            }
        });

        Consumer<List<TeachingClassStudent>> consumer = o -> teachingClassStudentMapper.addBatch(o);
        BatchInsert.batchSplitInsert(teachingClassStudentList, consumer);

        return "添加成功";
    }

    private List<SegmentByClassDTO> getSegmentListByClass(Integer taskId, String classId) {

        List<SegmentByClassDTO> segmentByClassDTOS = new ArrayList<>();

        List<PlanTeachingToStudent> planTeachingToStudentList = planTeachingStudentMapper.selectPlanTeachingToStudentList(taskId, Deleted.NOT.getCode());

        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentMapper.selectPlanTeachingCourseSegmentList(taskId, Deleted.NOT.getCode());

        List<PlanTeachingCourseSegment> planTeachingCourseSegmentList = planTeachingCourseSegments.stream().filter(p -> p.getFlag().equals(2)).collect(Collectors.toList());

        List<PlanTeaching> planTeachings = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId)
                .eq(PlanTeaching::getDeleted, Deleted.NOT.getCode()).list();

        List<PlanTeachingToStudent> planTeachingToStudents = planTeachingToStudentList.stream()
                .filter(p -> p.getClassId().equals(classId)).collect(Collectors.toList());


        List<PlanTeaching> pTeaching = planTeachings.stream()
                .filter(p -> planTeachingToStudents.stream().anyMatch(o -> p.getBaseTeachingPlanId().equals(o.getBaseTeachingPlanId())))
                .collect(Collectors.toList());

        List<String> planTeachingIds = pTeaching.stream().map(PlanTeaching::getBaseTeachingPlanId).distinct().collect(Collectors.toList());

        List<PlanTeachingCourseSegment> courseSegmentList = planTeachingCourseSegmentList.stream()
                .filter(p -> planTeachingIds.stream().anyMatch(o -> o.equals(p.getBaseTeachingPlanId()))).collect(Collectors.toList());


        List<Segment> segments = segmentMapper.getSegmentList(taskId);


        Set<String> baseSegment = new HashSet<>();
        if (CollUtil.isNotEmpty(pTeaching)) {
            for (PlanTeaching planTeaching : pTeaching) {

                List<PlanTeachingCourseSegment> pTeachingCourseSegments = planTeachingCourseSegmentList.stream()
                        .filter(p -> p.getBaseTeachingPlanId().equals(planTeaching.getBaseTeachingPlanId())
                                && p.getFlag() == 2).collect(Collectors.toList());

                if (CollUtil.isNotEmpty(pTeachingCourseSegments)) {
                    for (PlanTeachingCourseSegment pTeachingCourseSegment : pTeachingCourseSegments) {
                        if (!baseSegment.contains(pTeachingCourseSegment.getBaseCourseId())) {
                            baseSegment.add(pTeachingCourseSegment.getBaseCourseId());
                        }
                    }
                }
            }
        }

        //判断环节是否被禁用
        List<Segment> segmentList = new ArrayList<>();
        if (CollUtil.isNotEmpty(baseSegment)) {
            for (String c : baseSegment) {
                Segment segment = segments.stream()
                        .filter(p -> p.getBaseSegmentId().equals(c))
                        .findFirst().orElse(null);

                if (segment != null) {

                    List<String> basePlanTeachings = courseSegmentList.stream().filter(p -> p.getBaseCourseId().equals(segment.getBaseSegmentId())).collect(Collectors.toList())
                            .stream().map(PlanTeachingCourseSegment::getBaseTeachingPlanId).distinct().collect(Collectors.toList());
                    List<PlanTeaching> planTeachingList = pTeaching.stream().filter(p -> basePlanTeachings.stream()
                            .anyMatch(o -> o.equals(p.getBaseTeachingPlanId())))
                            .collect(Collectors.toList());

                    SegmentByClassDTO segmentByClassDTO = new SegmentByClassDTO();
                    segmentByClassDTO.setSegmentId(segment.getSegmentId());
                    segmentByClassDTO.setSegmentName(segment.getSegmentName());
                    List<String> studensList = new ArrayList<>();
                    List<String> baseTeachingPlanId = new ArrayList<>();
                    if (CollUtil.isNotEmpty(planTeachingList)) {
                        planTeachingList.forEach(o -> {
                            List<PlanTeachingToStudent> planTeachingToStudentList1 = planTeachingToStudentList.stream().filter(p -> p.getClassId().equals(classId)
                                    && p.getBaseTeachingPlanId().equals(o.getBaseTeachingPlanId())).collect(Collectors.toList());
                            List<String> baseStudentIds = planTeachingToStudentList1.stream().map(PlanTeachingToStudent::getBaseStudentId).distinct().collect(Collectors.toList());
                            studensList.addAll(baseStudentIds);
                            StringBuilder sb = new StringBuilder();
                            sb.append(o.getMajorName()).append("-").append(o.getGradeName()).append("-").append(o.getMajorVersionName());
                            baseTeachingPlanId.add(sb.toString());
                        });

                    }

                    String collect = baseTeachingPlanId.stream().collect(Collectors.joining(","));
                    segmentByClassDTO.setBaseTeachingPlanId(collect);
                    segmentByClassDTO.setBaseStudentId(studensList);
                    segmentByClassDTOS.add(segmentByClassDTO);
                    segmentList.add(segment);
                }


            }
        }

        List<ClassCourseClose> classCourseCloses = classCourseCloseService.lambdaQuery()
                .eq(ClassCourseClose::getTaskId, taskId).eq(ClassCourseClose::getClassId, classId).eq(ClassCourseClose::getFlag, 2)
                .eq(ClassCourseClose::getDeleted, Deleted.YES.getCode()).list();

        List<Long> segmentIds = classCourseCloses.stream().map(ClassCourseClose::getCourseId).distinct().collect(Collectors.toList());

        List<Segment> segmentUnEnable = segmentList.stream().filter(p -> segmentIds.stream().anyMatch(o -> p.getSegmentId().equals(o))).collect(Collectors.toList());

        List<SegmentByClassDTO> segmentByClassDTOSUnable = segmentByClassDTOS.stream().filter(p -> segmentIds.stream().anyMatch(m -> m.equals(p.getSegmentId()))).collect(Collectors.toList());

        segmentByClassDTOS.removeAll(segmentByClassDTOSUnable);

        segmentList.removeAll(segmentUnEnable);

        return segmentByClassDTOS;
    }

    private List<CourseByClassDTO> getCourseListByClass(Integer taskId, String classId) {

        List<CourseByClassDTO> courseByClassDTOList = new ArrayList<>();

        List<PlanTeachingToStudent> planTeachingToStudentList = planTeachingStudentMapper.selectPlanTeachingToStudentList(taskId, Deleted.NOT.getCode());

        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentMapper.selectPlanTeachingCourseSegmentList(taskId, Deleted.NOT.getCode());

        List<PlanTeachingCourseSegment> planTeachingCourseSegmentList = planTeachingCourseSegments.stream().filter(p -> p.getFlag().equals(1)).collect(Collectors.toList());

        List<PlanTeaching> planTeachings = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId)
                .eq(PlanTeaching::getDeleted, Deleted.NOT.getCode()).list();

        List<PlanTeachingToStudent> planTeachingToStudents = planTeachingToStudentList.stream()
                .filter(p -> p.getClassId().equals(classId)).collect(Collectors.toList());


        List<PlanTeaching> pTeaching = planTeachings.stream()
                .filter(p -> planTeachingToStudents.stream().anyMatch(o -> p.getBaseTeachingPlanId().equals(o.getBaseTeachingPlanId())))
                .collect(Collectors.toList());

        List<String> planTeachingIds = pTeaching.stream().map(PlanTeaching::getBaseTeachingPlanId).distinct().collect(Collectors.toList());

        List<PlanTeachingCourseSegment> courseSegmentList = planTeachingCourseSegmentList.stream()
                .filter(p -> planTeachingIds.stream().anyMatch(o -> o.equals(p.getBaseTeachingPlanId()))).collect(Collectors.toList());

        List<Course> courses = courseMapper.getCourseList(taskId);


        Set<String> baseCourse = new HashSet<>();
        //判断课程是否被启用
        List<Course> courseList = new ArrayList<>();
        if (CollUtil.isNotEmpty(pTeaching)) {
            for (PlanTeaching planTeaching : pTeaching) {

                List<PlanTeachingCourseSegment> pTeachingCourseSegments = planTeachingCourseSegmentList.stream()
                        .filter(p -> p.getBaseTeachingPlanId().equals(planTeaching.getBaseTeachingPlanId())
                                && planTeaching.getDeleted().equals(Deleted.NOT.getCode()) && p.getDeleted().equals(Deleted.NOT.getCode())
                                && p.getFlag() == 1).collect(Collectors.toList());


                if (CollUtil.isNotEmpty(pTeachingCourseSegments)) {
                    for (PlanTeachingCourseSegment pTeachingCourseSegment : pTeachingCourseSegments) {
                        if (!baseCourse.contains(pTeachingCourseSegment.getBaseCourseId())) {
                            baseCourse.add(pTeachingCourseSegment.getBaseCourseId());
                        }
                    }
                }
            }
        }


        //判断课程是否被启用
        if (CollUtil.isNotEmpty(baseCourse)) {
            for (String c : baseCourse) {
                Course course = courses.stream()
                        .filter(p -> p.getBaseCourseId().equals(c))
                        .findFirst().orElse(null);

                if (course != null) {
                    List<String> basePlanTeachings = courseSegmentList.stream().filter(p -> p.getBaseCourseId().equals(course.getBaseCourseId())).collect(Collectors.toList())
                            .stream().map(PlanTeachingCourseSegment::getBaseTeachingPlanId).distinct().collect(Collectors.toList());
                    List<PlanTeaching> planTeachingList = pTeaching.stream().filter(p -> basePlanTeachings.stream()
                            .anyMatch(o -> o.equals(p.getBaseTeachingPlanId())))
                            .collect(Collectors.toList());
                    CourseByClassDTO courseByClassDTO = new CourseByClassDTO();
                    courseByClassDTO.setCourseId(course.getCourseId());
                    courseByClassDTO.setCourseName(course.getCourseName());
                    List<String> studentsList = new ArrayList<>();
                    List<String> baseTeachingPlanId = new ArrayList<>();
                    if (CollUtil.isNotEmpty(planTeachingList)) {
                        planTeachingList.forEach(o -> {
                            List<PlanTeachingToStudent> planTeachingToStudentList1 = planTeachingToStudentList.stream().filter(p -> p.getClassId().equals(classId)
                                    && p.getBaseTeachingPlanId().equals(o.getBaseTeachingPlanId())).collect(Collectors.toList());
                            List<String> baseSteudent = planTeachingToStudentList1.stream().map(PlanTeachingToStudent::getBaseStudentId).distinct().collect(Collectors.toList());
                            studentsList.addAll(baseSteudent);

                            StringBuilder sb = new StringBuilder();
                            sb.append(o.getMajorName()).append("-").append(o.getGradeName()).append("-").append(o.getMajorVersionName());
                            baseTeachingPlanId.add(sb.toString());
                        });
                    }

                    String collect = baseTeachingPlanId.stream().collect(Collectors.joining(","));
                    courseByClassDTO.setBaseTeachingPlanId(collect);
                    courseByClassDTO.setBaseStudentId(studentsList);
                    courseByClassDTOList.add(courseByClassDTO);
                    courseList.add(course);
                }
            }
        }

        List<ClassCourseClose> classCourseCloses = classCourseCloseService.lambdaQuery()
                .eq(ClassCourseClose::getTaskId, taskId)
                .eq(ClassCourseClose::getClassId, classId)
                .eq(ClassCourseClose::getFlag, 1)
                .eq(ClassCourseClose::getDeleted, Deleted.YES.getCode()).list();

        List<Long> courseIds = classCourseCloses.stream().map(ClassCourseClose::getCourseId).distinct().collect(Collectors.toList());

        List<Course> courseUnEnable = courseList.stream().filter(p -> courseIds.stream().anyMatch(o -> p.getCourseId().equals(o))).collect(Collectors.toList());

        List<CourseByClassDTO> courseByClassDTOSUnable = courseByClassDTOList.stream()
                .filter(p -> courseIds.stream().anyMatch(m -> m.equals(p.getCourseId()))).collect(Collectors.toList());

        courseByClassDTOList.removeAll(courseByClassDTOSUnable);

        courseList.removeAll(courseUnEnable);

        return courseByClassDTOList;
    }

    /**
     * 获得生成的教学班信息
     *
     * @param taskId
     * @param gradeId
     * @param majorId
     * @param courseType
     * @param keyword
     * @return
     */
    @Override
    public TeachingClassDtoVo getTeachingClassList(Integer taskId, String gradeId, String majorId, Integer courseType, String keyword) {


        TeachingClassDtoVo teachingClassDtoVo = new TeachingClassDtoVo();

        List<TeachingClassDto> teachingClassDtos = new ArrayList<>();


        List<Long> majorIds = new ArrayList<>();
        if (StringUtils.isNotBlank(majorId)) {
            List<Major> ml = majorMapper.selectList(new LambdaQueryWrapper<Major>().eq(Major::getTaskId, taskId).eq(Major::getBaseMajorId, majorId)
                    .eq(Major::getDeleted, Deleted.NOT.getCode()));
            majorIds = ml.stream().map(Major::getMajorId).distinct().collect(Collectors.toList());
        }

        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(StringUtils.isNotBlank(gradeId), TeachingClass::getGradeId, gradeId)
                .eq(ObjUtil.isNotNull(courseType), TeachingClass::getFlag, courseType)
                .isNull(TeachingClass::getUniqueShiftSign)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                .and(StrUtil.isNotBlank(keyword), wrapper -> wrapper.like(TeachingClass::getCourseName, keyword)));


        List<Course> courseList = courseMapper.selectList(new LambdaQueryWrapper<Course>().eq(Course::getTaskId, taskId)
                .eq(Course::getDeleted, Deleted.NOT.getCode()));

        List<Segment> segmentList = segmentMapper.selectList(new LambdaQueryWrapper<Segment>().eq(Segment::getTaskId, taskId)
                .eq(Segment::getDeleted, Deleted.NOT.getCode()));

        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId));


        List<PlanTeachingCourseSegment> planTeachingCourseSegmentList = planTeachingCourseSegmentMapper
                .selectList(new LambdaQueryWrapper<PlanTeachingCourseSegment>().eq(PlanTeachingCourseSegment::getTaskId, taskId)
                        .eq(PlanTeachingCourseSegment::getDeleted, Deleted.NOT.getCode()));


        List<PlanTeaching> planTeachingList = planTeachingMapper.selectList(new LambdaQueryWrapper<PlanTeaching>().eq(PlanTeaching::getTaskId, taskId)
                .eq(PlanTeaching::getDeleted, Deleted.NOT.getCode()));


        List<PlanTeachingStudent> planTeachingStudentList = planTeachingStudentMapper.selectList(new LambdaQueryWrapper<PlanTeachingStudent>()
                .eq(PlanTeachingStudent::getTaskId, taskId).eq(PlanTeachingStudent::getDeleted, Deleted.NOT.getCode()));


        List<Student> studentList = studentMapper.selectList(new LambdaQueryWrapper<Student>().eq(Student::getTaskId, taskId).eq(Student::getDeleted, Deleted.NOT.getCode()));


        List<Major> mList = majorMapper.selectList(new LambdaQueryWrapper<Major>().eq(Major::getTaskId, taskId).eq(Major::getDeleted, Deleted.NOT.getCode()));

        List<ClassCourseClose> classCourseCloseList = classCourseCloseService.lambdaQuery().eq(ClassCourseClose::getTaskId, taskId)
                .eq(ClassCourseClose::getDeleted, Deleted.NOT.getCode()).list();

        List<Long> teachingClassIds = teachingClassList.stream()
                .map(TeachingClass::getTeachingClassId)
                .distinct().collect(Collectors.toList());


        List<TeachingClassWeek> teachingClassWeeks = new ArrayList<>();
        if (CollUtil.isNotEmpty(teachingClassIds)) {
            teachingClassWeeks = teachingClassWeekService.lambdaQuery()
                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode())
                    .in(TeachingClassWeek::getTeachingClassId, teachingClassIds).list();
        }

        List<TeachingClassTeacher> teachingClassTeachers = teachingClassTeacherService.lambdaQuery()
                .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()).list();


        Map<String, List<TeachingClass>> gradeMap = teachingClassList.stream().collect(Collectors.groupingBy(TeachingClass::getGradeId));


        //todo 对选课进行过滤筛选
        List<TeachingClassWeek> finalTeachingClassWeeks = teachingClassWeeks;
        gradeMap.forEach((key, value) -> {
            TeachingClassDto teachingClassDto = new TeachingClassDto();
            teachingClassDto.setGradeId(key);
            TeachingClass gradeTeaching = value.get(0);
            teachingClassDto.setGradeName(gradeTeaching.getGradeName());
            List<MajorList> majorListList = new ArrayList<>();
            Map<Long, List<TeachingClass>> majorMap = value.stream().collect(Collectors.groupingBy(TeachingClass::getMajorId));
            majorMap.forEach((m, t) -> {
                MajorList majorList = new MajorList();
                majorList.setMajorId(m);
                TeachingClass majorTeaching = t.get(0);
                majorList.setMajorName(majorTeaching.getMajorName());
                List<ClassDto> classDtoList = new ArrayList<>();
                Map<Long, List<TeachingClass>> courseMap = t.stream().collect(Collectors.groupingBy(TeachingClass::getCourseId));
                courseMap.forEach((c, cm) -> {

                    List<Long> tIds = cm.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());

                    List<TeachingClassTeacher> teachingClassTeacherList = teachingClassTeachers.stream()
                            .filter(p -> tIds.stream().anyMatch(tIDs -> p.getTeachingClassId().equals(tIDs))).collect(Collectors.toList());

                    List<Long> teacherIds = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherId)
                            .distinct().collect(Collectors.toList());

                    List<String> stringTeacherIds = teacherIds.stream()
                            .map(String::valueOf)
                            .collect(Collectors.toList());

                    List<String> teacherNames = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherName).distinct().collect(Collectors.toList());

                    String teacherIdsString = String.join("、", stringTeacherIds);

                    String teacherNameString = String.join("、", teacherNames);


                    Course course = courseList.stream().filter(p -> p.getCourseId().equals(c)).findFirst().orElse(null);

                    Segment segment = segmentList.stream().filter(p -> p.getSegmentId().equals(c)).findFirst().orElse(null);

                    if (course != null) {
                        ClassDto classDto = new ClassDto();
                        classDto.setCourseId(c);
                        classDto.setTeacherId(teacherIdsString);
                        classDto.setTeacherName(teacherNameString);
                        classDto.setCourseType(course.getCourseType());
                        classDto.setCourseTypeId(course.getCourseTypeId());
                        classDto.setCourseName(course.getCourseName());
                        classDto.setCourseNature(course.getCourseNature());
                        classDto.setFlag(0);
                        int isEnAble = cm.stream().mapToInt(TeachingClass::getIsEnable).sum();
                        classDto.setIsEnable(isEnAble > 0 ? 1 : 0);
                        int isChoose = cm.stream().mapToInt(TeachingClass::getTeachingClassType).sum();
                        classDto.setIsChooseCourse(isChoose > 0 ? 1 : 0);

                        List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentList.stream().filter(p -> p.getBaseCourseId().equals(course.getBaseCourseId())).collect(Collectors.toList());

                        List<String> planTeachingIds = planTeachingCourseSegments.stream().map(PlanTeachingCourseSegment::getBaseTeachingPlanId).distinct().collect(Collectors.toList());

                        List<Major> majors = mList.stream().filter(p -> p.getMajorId().equals(m)).collect(Collectors.toList());


                        //通过培养计划获取对应教学班
                        if (CollUtil.isNotEmpty(majors)) {
                            Major major = majors.get(0);

                            List<PlanTeaching> planTeachings = planTeachingList.stream()
                                    .filter(p -> planTeachingIds.stream().anyMatch(o -> o.equals(p.getBaseTeachingPlanId())))
                                    .collect(Collectors.toList())
                                    .stream().filter(p -> p.getGradeId().equals(key)
                                            && p.getBaseMajorId().equals(major.getBaseMajorId())).collect(Collectors.toList());

                            List<String> basePlanTeachingIds = planTeachings.stream().map(PlanTeaching::getBaseTeachingPlanId).distinct().collect(Collectors.toList());

                            List<PlanTeachingStudent> planTeachingStudents = planTeachingStudentList.stream().filter(p -> basePlanTeachingIds.stream()
                                    .anyMatch(o -> o.equals(p.getBaseTeachingPlanId()))).collect(Collectors.toList());
                            List<String> baseStudentIds = planTeachingStudents.stream().map(PlanTeachingStudent::getBaseStudentId).distinct().collect(Collectors.toList());
                            List<Student> students = studentList.stream().filter(p -> baseStudentIds.stream().anyMatch(o -> o.equals(p.getBaseStudentId()))).collect(Collectors.toList());
                            List<String> classIds = students.stream().map(Student::getClassId).distinct().collect(Collectors.toList());
                            List<ClassInfo> classInfos = classInfoList.stream().filter(p -> classIds.stream().anyMatch(a -> a.equals(p.getClassId()))).collect(Collectors.toList());

                            List<ClassCourseClose> classCourseCloses = classCourseCloseList.stream().filter(p -> p.getGradeId().equals(key)
                                    && p.getMajorId().equals(m) && p.getCourseId().equals(course.getCourseId())).collect(Collectors.toList());

                            List<String> deletedClassIds = classCourseCloses.stream().map(ClassCourseClose::getClassId).distinct().collect(Collectors.toList());

                            List<ClassInfo> deletedClassInfos = classInfos.stream().filter(p -> deletedClassIds.stream()
                                    .anyMatch(o -> o.equals(p.getClassId()))).distinct().collect(Collectors.toList());
                            classInfos.removeAll(deletedClassInfos);
                            classDto.setClassInfoList(classInfos);

                        }


                        classDto.setTeachingClassList(cm);
                        classDto.setCredit(course.getCredit());
                        TeachingClass teachingClass = cm.get(0);

                        List<WeekDto> weekDtos = new ArrayList<>();

                        List<TeachingClassWeek> teachingClassWeekList = finalTeachingClassWeeks.stream()
                                .filter(p -> p.getTeachingClassId()
                                        .equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());

                        teachingClassWeekList.forEach(o -> {
                            WeekDto weekDto = new WeekDto();

                            weekDto.setAssessmentId(o.getAssessmentId());
                            weekDto.setAssessmentName(o.getAssessmentName());
                            weekDto.setHourType(o.getHourType());
                            weekDto.setWeek(o.getWeek());
                            Integer weekNum = getOneNumber(o.getWeek());
                            weekDto.setTotalStudyHour(weekNum * o.getWeekNum());
                            weekDto.setRoomType(o.getRoomType());
                            weekDto.setRoomId(o.getRoomId());
                            weekDto.setRoomTypeName(GlobalConstant.roomTypeMap.get(o.getRoomType()));

                            weekDto.setWeekNum(o.getWeekNum());
                            weekDto.setConnectNumber(o.getConnectNumber());
                            weekDto.setConnectSection(o.getConnectSection());
                            weekDtos.add(weekDto);

                        });
                        classDto.setWeekDtoList(weekDtos);
                        classDtoList.add(classDto);
                    }


                    if (segment != null) {
                        ClassDto classDto = new ClassDto();
                        classDto.setCourseId(c);
                        classDto.setTeacherId(teacherIdsString);
                        classDto.setTeacherName(teacherNameString);
                        classDto.setCourseTypeId(segment.getSegmentTypeId());
                        classDto.setCourseType(segment.getSegmentType());
                        classDto.setCourseName(segment.getSegmentName());
                        classDto.setFlag(1);
                        int isEnAble = cm.stream().mapToInt(TeachingClass::getIsEnable).sum();
                        classDto.setIsEnable(isEnAble > 0 ? 1 : 0);

                        List<String> classIds = cm.stream().map(TeachingClass::getClassId).distinct().collect(Collectors.toList());

                        List<ClassInfo> classInfos = classInfoList.stream().filter(p -> classIds.stream().anyMatch(a -> Long.valueOf(a).equals(p.getId()))).collect(Collectors.toList());
                        classDto.setClassInfoList(classInfos);
                        classDto.setTeachingClassList(cm);
                        classDto.setCredit(segment.getCredit());
                        TeachingClass teachingClass = cm.get(0);

                        List<WeekDto> weekDtos = new ArrayList<>();

                        List<TeachingClassWeek> teachingClassWeekList = finalTeachingClassWeeks.stream()
                                .filter(p -> p.getTeachingClassId()
                                        .equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());

                        teachingClassWeekList.forEach(o -> {
                            WeekDto weekDto = new WeekDto();
                            weekDto.setWeek(o.getWeek());
                            weekDtos.add(weekDto);

                        });
                        classDto.setWeekDtoList(weekDtos);
                        classDtoList.add(classDto);
                    }
                });
            });

            teachingClassDtos.add(teachingClassDto);
        });

        List<Long> courseIds = teachingClassList.stream().map(TeachingClass::getCourseId).distinct().collect(Collectors.toList());
        teachingClassDtoVo.setTotalCourse((long) courseIds.size());
        List<TeachingClass> unStateTeachingClass = teachingClassList.stream().filter(p -> p.getState().equals(0)).collect(Collectors.toList());
        teachingClassDtoVo.setNoComplete((long) unStateTeachingClass.size());
        teachingClassDtoVo.setComplete((long) (teachingClassList.size() - unStateTeachingClass.size()));
        teachingClassDtoVo.setTeachingClassDtos(teachingClassDtos);


        return teachingClassDtoVo;
    }

    /**
     * 修改是否需要选课
     *
     * @param taskId
     * @param gradeId
     * @param courseId
     * @param courseType
     * @param teachingClassType
     * @return
     */
    @Override
    public Integer updateTeachingClassType(Integer taskId, String gradeId, Integer courseId, Integer courseType, Integer teachingClassType) {

        if (courseType == 1) {
            teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                    .eq(TeachingClass::getTaskId, taskId)
                    .eq(StringUtils.isNotBlank(gradeId), TeachingClass::getGradeId, gradeId)
                    .eq(ObjUtil.isNotNull(courseType), TeachingClass::getFlag, 1)
                    .eq(ObjUtil.isNotNull(courseId), TeachingClass::getCourseId, courseId)
                    .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                    .set(TeachingClass::getDeleted, Deleted.YES.getCode()));

            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                    .eq(ParameterSetting::getTaskId, taskId).eq(StringUtils.isNotBlank(gradeId), ParameterSetting::getGradeId, gradeId)
                    .eq(ObjUtil.isNotNull(courseType), ParameterSetting::getFlag, 1)
                    .eq(ObjUtil.isNotNull(courseId), ParameterSetting::getCourseId, courseId)
                    .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                    .set(ParameterSetting::getTeachingClassType, teachingClassType));
        } else {
            teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                    .eq(TeachingClass::getTaskId, taskId)
                    .eq(StringUtils.isNotBlank(gradeId), TeachingClass::getGradeId, gradeId)
                    .eq(ObjUtil.isNotNull(courseType), TeachingClass::getFlag, 2)
                    .eq(ObjUtil.isNotNull(courseId), TeachingClass::getCourseId, courseId)
                    .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                    .set(TeachingClass::getDeleted, Deleted.YES.getCode()));

            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                    .eq(ParameterSetting::getTaskId, taskId).eq(StringUtils.isNotBlank(gradeId), ParameterSetting::getGradeId, gradeId)
                    .eq(ObjUtil.isNotNull(courseType), ParameterSetting::getFlag, 2)
                    .eq(ObjUtil.isNotNull(courseId), ParameterSetting::getCourseId, courseId)
                    .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                    .set(ParameterSetting::getTeachingClassType, teachingClassType));
        }

        return 0;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String modifyTeachingClassNum(Integer taskId, ModifyTeachingClassNumDto modifyTeachingClassNumDto) {
        if (modifyTeachingClassNumDto.getNums() == 0) {
            return "班级设置不可以为0个";
        }
        List<TeachingClass> teachingClassList = new ArrayList<>();
        List<String> collect1 = modifyTeachingClassNumDto.getClassInfoList().stream().map(String::valueOf).collect(Collectors.toList());

        List<TeachingClass> inputTeachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getGradeId, modifyTeachingClassNumDto.getGradeId())
                .eq(TeachingClass::getCourseId, modifyTeachingClassNumDto.getCourseId())
                .in(TeachingClass::getClassId, collect1)
                .isNull(TeachingClass::getUniqueShiftSign)
                .eq(TeachingClass::getTeachingClassType, TeachingClassType.NOSELECT.getCode()));


        //需要删除的选课教学班
        List<TeachingClass> deletedTeachingClass = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>().eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getGradeId, modifyTeachingClassNumDto.getGradeId())
                .eq(TeachingClass::getCourseId, modifyTeachingClassNumDto.getCourseId())
                .eq(TeachingClass::getTeachingClassType, TeachingClassType.SELECT.getCode())
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        List<Long> deletedTeachingClassIds = deletedTeachingClass.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());


        List<TeachingClassWeek> teachingClassWeeks = new ArrayList<>();


        /**
         * 对应班级人数
         */
        List<Integer> classNum = inputTeachingClassList.stream().map(TeachingClass::getClassNum).collect(Collectors.toList());

        int count = 0;

        for (Integer num : classNum) {
            count += num;
        }


        int number = count / (modifyTeachingClassNumDto.getNums() != 0 ? modifyTeachingClassNumDto.getNums() : 1);


        List<Long> teachingClassIds = inputTeachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct()
                .collect(Collectors.toList());

        TeachingClass teachingClass2 = inputTeachingClassList.get(0);

        List<TeachingClassWeek> teachingClassWeekList = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>().eq(TeachingClassWeek::getTeachingClassId, teachingClass2.getTeachingClassId()));


        TaskInfo taskInfo = taskInfoService.getById(taskId);
        List<Teacher> teacherList = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().eq(Teacher::getSchoolId, taskInfo.getSchoolId()).eq(Teacher::getTerm, taskInfo.getTerm()));


        List<ParameterSetting> parameterSettingList = parameterSettingMapper.selectList(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                .eq(ParameterSetting::getGradeId, teachingClass2.getGradeId())
                .eq(ParameterSetting::getCourseId, teachingClass2.getCourseId()));


        int state = 0;
        int sum = parameterSettingList.stream().mapToInt(ParameterSetting::getState).sum();
        state = sum != parameterSettingList.size() ? 0 : 1;


        WeekDateVo weekDateVo = taskInfoService.countWeek(taskId);
        long weekCount = weekDateVo.getWeekCount();
        String result = LongStream.range(0, weekCount).mapToObj(i -> "1").reduce((s1, s2) -> s1 + s2).orElse("");

        if (CollUtil.isNotEmpty(inputTeachingClassList)) {
            TeachingClass teachingClass = inputTeachingClassList.get(0);

            if (modifyTeachingClassNumDto.getNums() != 0) {

                for (int i = 0; i < modifyTeachingClassNumDto.getNums(); i++) {
                    TeachingClass teachingClass1 = new TeachingClass();
                    teachingClass1.setTaskId(taskId);
                    teachingClass1.setTeachingClassName(teachingClass.getGradeName() + teachingClass.getCourseName() + "选课" + (i + 1) + "班");
                    teachingClass1.setCourseId(teachingClass.getCourseId());
                    teachingClass1.setCourseName(teachingClass.getCourseName());
                    teachingClass1.setGradeId(teachingClass.getGradeId());
                    teachingClass1.setGradeName(teachingClass.getGradeName());
                    teachingClass1.setClassNum(number);
                    teachingClass1.setFlag(teachingClass.getFlag());
                    teachingClass1.setState(state);
                    teachingClass1.setTeachingClassType(TeachingClassType.SELECT.getCode());
                    teachingClass1.setCampusId(teachingClass.getCampusId());
                    teachingClass1.setCampusName(teachingClass.getCampusName());
                    teachingClass1.setIsEnable(IsEnable.ENABLE.getCode());
                    teachingClassList.add(teachingClass1);
                }

                //添加第一次未分配完的学生
                if (count % modifyTeachingClassNumDto.getNums() != 0) {
                    int a = count % modifyTeachingClassNumDto.getNums();
                    for (int i = 0; i < a; i++) {
                        teachingClassList.get(i).setClassNum(teachingClassList.get(i).getClassNum() + 1);
                    }
                }
            }

            //通过传入的gradeId majorId 和courseId删除对应的教学班


            if (CollUtil.isNotEmpty(deletedTeachingClassIds)) {


                teachingClassMapper.delete(new LambdaQueryWrapper<TeachingClass>()
                        .in(TeachingClass::getTeachingClassId, deletedTeachingClassIds));


                teachingClassWeekMapper.delete(new LambdaQueryWrapper<TeachingClassWeek>()
                        .in(TeachingClassWeek::getTeachingClassId, deletedTeachingClassIds));


                teachingClassStudentMapper.delete(new LambdaQueryWrapper<TeachingClassStudent>()
                        .in(TeachingClassStudent::getTeachingClassId, deletedTeachingClassIds));


                teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>()
                        .in(TeachingClassTeacher::getTeachingClassId, deletedTeachingClassIds));

            }

        }

        //批量添加新学生
        teachingClassService.saveBatch(teachingClassList);


        List<TeachingClassTeacher> teachingClassTeacherList1 = new ArrayList<>();

        for (TeachingClass teachingClass : teachingClassList) {

            parameterSettingList.forEach(tw -> {
                TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                teachingClassWeek.setAssessmentId(tw.getAssessmentMethodId());
                teachingClassWeek.setAssessmentName(tw.getAssessmentMethod());
                teachingClassWeek.setRoomType(tw.getRoomType());
                teachingClassWeek.setTeachingClassId(teachingClass.getTeachingClassId());
                teachingClassWeek.setHourType(tw.getHourType());
                teachingClassWeek.setWeek(tw.getWeek());
                teachingClassWeek.setWeekNum(tw.getWeekNum());
                teachingClassWeek.setSign(tw.getSign());
                teachingClassWeek.setStartWeek(tw.getStartWeek());
                teachingClassWeek.setEndWeek(tw.getEndWeek());
                teachingClassWeek.setConnectNumber(tw.getConnectNumber());
                teachingClassWeek.setConnectSection(tw.getConnectSection());
                teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                teachingClassWeeks.add(teachingClassWeek);
            });

        }


        if (CollUtil.isNotEmpty(parameterSettingList)) {

            parameterSettingList.forEach(o -> {
                if (StringUtils.isNotBlank(o.getTeacherId())) {
                    List<TeachingClassTeacher> teachingClassTeacherList = new ArrayList<>();
                    List<String> strings = Arrays.asList(o.getTeacherId().split(","));
                    List<Long> collect = strings.stream().map(Long::valueOf).collect(Collectors.toList());

                    List<Long> collect2 = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());
                    AssignTeachersDto assignTeachersDto = new AssignTeachersDto();
                    assignTeachersDto.setClassInfoList(modifyTeachingClassNumDto.getClassInfoList());
                    assignTeachersDto.setTeacherIds(collect2);
                    assignTeachersDto.setIsChooseCourse(1);
                    assignTeachersDto.setHourType(o.getHourType());
                    assignTeachersDto.setTeacherIds(collect);

                    Integer teacherNum = assignTeachersDto.getTeacherIds().size();

                    Integer teachingClassNum = teachingClassList.size();

                    TeachingClass teachingClass1 = teachingClassList.get(0);


                    //开始设置教师
                    List<Teacher> teachers = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>()
                            .in(Teacher::getTeacherId, assignTeachersDto.getTeacherIds())
                            .eq(Teacher::getDeleted, Deleted.NOT.getCode()));


                    //  如果教师数量大于教学班数量
                    if (teacherNum > teachingClassNum) {
                        for (int i = 0; i < teachers.size(); i++) {
                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(teachingClassList.get(i % teachingClassNum).getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teachers.get(i).getTeacherId());
                            teachingClassTeacher.setTeacherName(teachers.get(i).getTeacherName());
                            teachingClassTeacher.setTeacherType(o.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                        }


                        teachingClassTeacherService.saveBatch(teachingClassTeacherList);


                        teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                                .in(TeachingClass::getTeachingClassId, teachingClassIds)
                                .set(TeachingClass::getState, 1));


                        String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                        String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                                .eq(ParameterSetting::getGradeId, teachingClass1.getGradeId())
                                .eq(ParameterSetting::getCourseId, teachingClass1.getCourseId())
                                .eq(ParameterSetting::getHourType, o.getHourType())
                                .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                                .set(ParameterSetting::getTeacherId, tIds)
                                .set(ParameterSetting::getTeacherName, tNames)
                                .set(ParameterSetting::getState, 1));
                    } else {
                        for (int i = 0; i < teachingClassList.size(); i++) {

                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(teachingClassList.get(i).getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teachers.get((i % teacherNum)).getTeacherId());
                            teachingClassTeacher.setTeacherName(teachers.get(i % teacherNum).getTeacherName());
                            teachingClassTeacher.setTeacherType(o.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);

                        }
                        teachingClassTeacherService.saveBatch(teachingClassTeacherList);
                        teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>().in(TeachingClass::getTeachingClassId, teachingClassIds).set(TeachingClass::getState, 1));

                        String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                        String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                                .eq(ParameterSetting::getGradeId, teachingClass1.getGradeId())
                                .eq(ParameterSetting::getCourseId, teachingClass1.getCourseId())
                                .eq(ParameterSetting::getHourType, o.getHourType())
                                .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                                .set(ParameterSetting::getTeacherId, tIds)
                                .set(ParameterSetting::getTeacherName, tNames)
                                .set(ParameterSetting::getState, 1));
                    }
                }
            });
        }

        teachingClassWeekService.saveBatch(teachingClassWeeks);


        TeachingClass teachingClass = teachingClassList.get(0);
        String collect = teachingClassList.stream().map(TeachingClass::getTeachingClassId).map(String::valueOf).collect(Collectors.joining(","));

        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                .set(ParameterSetting::getTeachingClassIdList, collect));


        return "添加成功";

    }


    /**
     * 修改考核方式
     *
     * @param taskId
     * @param gradeId
     * @param courseId
     * @param assessmentId
     * @return
     */
    @Override
    public String modifyAssessment(Integer taskId, String gradeId, Long courseId, Long assessmentId) {
        //通过taskId ,gradeId,majorId,courseId查询对应的教学班
        List<TeachingClass> teachingClasses = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId).eq(TeachingClass::getGradeId, gradeId)
                .eq(TeachingClass::getCourseId, courseId)
                .eq(TeachingClass::getFlag, 1)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        //找到需要修改的教学班id
        List<Long> teachingClasssIds = teachingClasses.stream()
                .map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());


        //通过assessmentId找到对应的考核方式
        AssessmentMethod assessmentMethod = assessmentMethodMapper
                .selectOne(new LambdaQueryWrapper<AssessmentMethod>().eq(AssessmentMethod::getAssessmentId, assessmentId));

        if (assessmentMethod != null) {
            //修改teachingClassWeek对应的teachingClassId的考核方式
            teachingClassWeekService.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                    .in(TeachingClassWeek::getTeachingClassId, teachingClasssIds).eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode())
                    .set(TeachingClassWeek::getAssessmentId, assessmentId).set(TeachingClassWeek::getAssessmentName, assessmentMethod.getAssessmentName()));


            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>().eq(ParameterSetting::getGradeId, gradeId).eq(ParameterSetting::getCourseId, courseId).set(ParameterSetting::getAssessmentMethodId, assessmentMethod.getAssessmentId())
                    .set(ParameterSetting::getAssessmentMethod, assessmentMethod.getAssessmentName()));
        }

        return assessmentMethod != null ? assessmentMethod.getAssessmentName() : null;
    }

    /**
     * 添加授课方式
     *
     * @param taskId
     * @param hourTypeInput
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addHourType(Integer taskId, HourTypeInput hourTypeInput) {

        //通过taskId gradeId,majorId,courseId找到对应的教学班
        List<TeachingClass> teachingClasses = teachingClassMapper
                .selectList(new LambdaQueryWrapper<TeachingClass>()
                        .eq(TeachingClass::getTaskId, taskId)
                        .eq(TeachingClass::getGradeId, hourTypeInput.getGradeId())
                        .eq(TeachingClass::getCourseId, hourTypeInput.getCourseId())
                        .eq(TeachingClass::getFlag, 1)
                        .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        List<ParameterSetting> parameterSettingList = parameterSettingMapper
                .selectList(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                        .eq(ParameterSetting::getGradeId, hourTypeInput.getGradeId())
                        .eq(ParameterSetting::getFlag, 1)
                        .eq(ParameterSetting::getCourseId, hourTypeInput.getCourseId()));


        //根据获取的teachingClasses获取对应的teachingClassid
        List<Long> teachingIds = teachingClasses.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());


        List<TeachingClassWeek> teachingClassWeekList = new ArrayList<>();
        List<TeachingClassTeacher> teachingClassTeacherList1 = new ArrayList<>();


        //根据获取的teachingIds获取对于的teachingClassWeek
        if (CollUtil.isNotEmpty(teachingIds)) {
            List<TeachingClassTeacher> teachingClassTeacherList = teachingClassTeacherMapper.selectList(new LambdaQueryWrapper<TeachingClassTeacher>()
                    .in(TeachingClassTeacher::getTeachingClassId, teachingIds)
                    .eq(TeachingClassTeacher::getTeacherType, 1)
                    .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));


            //删除对应授课方式
            teachingClassWeekMapper.delete(new LambdaQueryWrapper<TeachingClassWeek>().in(TeachingClassWeek::getTeachingClassId, teachingIds)
                    .eq(TeachingClassWeek::getHourType, hourTypeInput.getHourType()));

            //删除对应的教师
            teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>()
                    .in(TeachingClassTeacher::getTeachingClassId, teachingIds)
                    .eq(TeachingClassTeacher::getTeacherType, hourTypeInput.getHourType()));


            for (Long teachingId : teachingIds) {
                TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                teachingClassWeek.setTeachingClassId(teachingId);
                teachingClassWeek.setWeek(hourTypeInput.getWeek());
                teachingClassWeek.setHourType(hourTypeInput.getHourType());
                teachingClassWeek.setRoomId(hourTypeInput.getRoomId());
                teachingClassWeek.setRoomType(hourTypeInput.getRoomType());
                teachingClassWeek.setWeekNum(hourTypeInput.getWeekNum());
                teachingClassWeek.setSign(hourTypeInput.getSign());
                teachingClassWeek.setStartWeek(hourTypeInput.getStartWeek());
                teachingClassWeek.setEndWeek(hourTypeInput.getEndWeek());
                teachingClassWeek.setConnectNumber(hourTypeInput.getConnectNumber());
                teachingClassWeek.setConnectSection(hourTypeInput.getConnectSection());
                teachingClassWeek.setAssessmentId(hourTypeInput.getAssessmentId());
                teachingClassWeek.setAssessmentName(hourTypeInput.getAssessmentName());
                teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                teachingClassWeekList.add(teachingClassWeek);

                List<TeachingClassTeacher> teachingClassTeachers = teachingClassTeacherList.stream().filter(p -> p.getTeachingClassId().equals(teachingId)).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(teachingClassTeachers)) {
                    teachingClassTeachers.forEach(o -> {
                        TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                        teachingClassTeacher.setTeachingClassId(teachingId);
                        teachingClassTeacher.setTeacherId(o.getTeacherId());
                        teachingClassTeacher.setTeacherName(o.getTeacherName());
                        teachingClassTeacher.setTeacherType(hourTypeInput.getHourType());
                        teachingClassTeacherList1.add(teachingClassTeacher);
                    });
                }
            }
        }


        Consumer<List<TeachingClassWeek>> studentConsumer = o -> teachingClassWeekMapper.addBatch(o);
        BatchInsert.batchSplitInsert(teachingClassWeekList, studentConsumer);

        teachingClassTeacherService.saveBatch(teachingClassTeacherList1);


        if (CollUtil.isNotEmpty(parameterSettingList)) {
            ParameterSetting parameterSetting = parameterSettingList.get(0);

            List<TeachingClassWeek> collect = teachingClassWeekList.stream()
                    .filter(p -> p.getHourType().equals(hourTypeInput.getHourType())).collect(Collectors.toList());

            if (CollUtil.isNotEmpty(collect)) {
                TeachingClassWeek teachingClassWeek = collect.get(0);
                ParameterSetting parameterSetting1 = new ParameterSetting();
                parameterSetting1.setTaskId(taskId);
                parameterSetting1.setTeachingClassId(parameterSetting.getTeachingClassId());
                parameterSetting1.setTeachingClassWeekId(teachingClassWeek.getId());
                parameterSetting1.setGradeId(parameterSetting.getGradeId());
                parameterSetting1.setGradeName(parameterSetting.getGradeName());
                parameterSetting1.setCourseId(parameterSetting.getCourseId());
                parameterSetting1.setCourseName(parameterSetting.getCourseName());
                parameterSetting1.setTeachingClassType(parameterSetting.getTeachingClassType());
                parameterSetting1.setClassIdList(parameterSetting.getClassIdList());
                parameterSetting1.setTeachingClassIdList(parameterSetting.getTeachingClassIdList());
                parameterSetting1.setCredit(parameterSetting.getCredit());
                parameterSetting1.setAssessmentMethod(StringUtils.isNotBlank(parameterSetting.getAssessmentMethod()) ? parameterSetting.getAssessmentMethod() : "");
                parameterSetting1.setAssessmentMethodId(ObjUtil.isNotNull(parameterSetting.getAssessmentMethodId()) ? parameterSetting.getAssessmentMethodId() : 0L);
                parameterSetting1.setHourType(hourTypeInput.getHourType());
                parameterSetting1.setTeacherId(StringUtils.isNotBlank(parameterSetting.getTeacherId()) ? parameterSetting.getTeacherId() : "");
                parameterSetting1.setTeacherName(StringUtils.isNotBlank(parameterSetting.getTeacherName()) ? parameterSetting.getTeacherName() : "");
                parameterSetting1.setRoomType(parameterSetting.getRoomType());
                parameterSetting1.setRoomId(ObjUtil.isNotNull(parameterSetting.getRoomId()) ? parameterSetting.getRoomId() : 0L);
                parameterSetting1.setWeek(teachingClassWeek.getWeek());
                parameterSetting1.setSign(teachingClassWeek.getSign());
                parameterSetting1.setStartWeek(hourTypeInput.getStartWeek());
                parameterSetting1.setEndWeek(hourTypeInput.getEndWeek());
                parameterSetting1.setWeekNum(teachingClassWeek.getWeekNum());
                parameterSetting1.setConnectSection(teachingClassWeek.getConnectSection());
                parameterSetting1.setConnectNumber(teachingClassWeek.getConnectNumber());
                parameterSetting1.setState(parameterSetting.getState());
                parameterSetting1.setIsEnable(IsEnable.ENABLE.getCode());
                parameterSetting1.setDeleted(Deleted.NOT.getCode());
                parameterSetting1.setFlag(parameterSetting.getFlag());
                parameterSettingService.save(parameterSetting1);
            }
        }


        return "添加成功";
    }

    /**
     * 删除授课方式
     *
     * @param taskId
     * @param hourTypeInput
     * @return
     */
    @Transactional
    @Override
    public String deletedHourType(Integer taskId, HourTypeInput hourTypeInput) {
        //通过taskId gradeId,majorId,courseId找到对应的教学班
        List<TeachingClass> teachingClasses = teachingClassMapper
                .selectList(new LambdaQueryWrapper<TeachingClass>()
                        .eq(TeachingClass::getTaskId, taskId)
                        .eq(TeachingClass::getGradeId, hourTypeInput.getGradeId())
                        .eq(TeachingClass::getFlag, 1)
                        .eq(TeachingClass::getCourseId, hourTypeInput.getCourseId())
                        .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


        //根据获取的teachingClasses获取对应的teachingClassid
        List<Long> teachingIds = teachingClasses.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());


        //根据获取的teachingIds获取对于的teachingClassWeek
        if (CollUtil.isNotEmpty(teachingIds)) {
            teachingClassWeekMapper.delete(new LambdaQueryWrapper<TeachingClassWeek>()
                    .in(TeachingClassWeek::getTeachingClassId, teachingIds)
                    .eq(TeachingClassWeek::getHourType, hourTypeInput.getHourType())
                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));


            teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>()
                    .in(TeachingClassTeacher::getTeachingClassId, teachingIds)
                    .eq(TeachingClassTeacher::getTeacherType, hourTypeInput.getHourType())
                    .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));
        }

        parameterSettingMapper.delete(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                .eq(ParameterSetting::getGradeId, hourTypeInput.getGradeId())
                .eq(ParameterSetting::getCourseId, hourTypeInput.getCourseId()).eq(ParameterSetting::getFlag, 1)
                .eq(ParameterSetting::getHourType, hourTypeInput.getHourType()));

        return "删除成功";
    }

    /**
     * 分配教师
     *
     * @param taskId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean assignTeachers(Integer taskId, AssignTeachersDto assignTeachersDto) {


        List<Long> teachingClassIds = new ArrayList<>();
        if (ObjUtil.isNull(assignTeachersDto.getIsChooseCourse()) || assignTeachersDto.getIsChooseCourse() == 1) {
            ParameterSetting parameterSetting = parameterSettingMapper.selectOne(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                    .eq(ParameterSetting::getGradeId, assignTeachersDto.getGradeId())
                    .eq(ParameterSetting::getCourseId, assignTeachersDto.getCourseId())
                    .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType()).eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()));

            if (ObjUtil.isNotNull(parameterSetting)) {
                teachingClassIds = new ArrayList<>(Arrays.asList(parameterSetting.getTeachingClassIdList().split(",")))
                        .stream().map(Long::valueOf).collect(Collectors.toList());
            }

            List<TeachingClass> teachingClassList = teachingClassMapper
                    .selectList(new LambdaQueryWrapper<TeachingClass>()
                            .eq(TeachingClass::getTaskId, taskId)
                            .in(TeachingClass::getTeachingClassId, teachingClassIds)
                            .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

            Integer teacherNum = assignTeachersDto.getTeacherIds().size();

            Integer teachingClassNum = teachingClassList.size();

            TeachingClass teachingClass = teachingClassList.get(0);

            //删除之前设置的教师
            teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>()
                    .in(TeachingClassTeacher::getTeachingClassId, teachingClassIds)
                    .eq(TeachingClassTeacher::getTeacherType, assignTeachersDto.getHourType()));

            //开始设置教师
            List<Teacher> teachers = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>()
                    .in(Teacher::getTeacherId, assignTeachersDto.getTeacherIds())
                    .eq(Teacher::getDeleted, Deleted.NOT.getCode()));

            List<TeachingClassTeacher> teachingClassTeacherList = new ArrayList<>();


            //  如果教师数量大于教学班数量
            if (teacherNum > teachingClassNum) {
                for (int i = 0; i < teachers.size(); i++) {
                    TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                    teachingClassTeacher.setTeachingClassId(teachingClassList.get(i % teachingClassNum).getTeachingClassId());
                    teachingClassTeacher.setTeacherId(teachers.get(i).getTeacherId());
                    teachingClassTeacher.setTeacherName(teachers.get(i).getTeacherName());
                    teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                    teachingClassTeacherList.add(teachingClassTeacher);
                }

                teachingClassTeacherService.saveBatch(teachingClassTeacherList);
                String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));


                if (teachingClass.getFlag().equals(2)) {
                    parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                            .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                            .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                            .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType())
                            .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                            .set(ParameterSetting::getTeacherId, tIds)
                            .set(ParameterSetting::getState, 1)
                            .set(ParameterSetting::getTeacherName, tNames));

                    teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                                    .eq(TeachingClass::getTaskId, taskId)
                                    .in(TeachingClass::getTeachingClassId, teachingClassIds)
                                    .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                                    .set(TeachingClass::getState, 1));

                }else{
                    parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                            .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                            .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                            .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType())
                            .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                            .set(ParameterSetting::getTeacherId, tIds)
                            .set(ParameterSetting::getTeacherName, tNames));
                }


            } else {
                for (int i = 0; i < teachingClassList.size(); i++) {

                    TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                    teachingClassTeacher.setTeachingClassId(teachingClassList.get(i).getTeachingClassId());
                    teachingClassTeacher.setTeacherId(teachers.get((i % teacherNum)).getTeacherId());
                    teachingClassTeacher.setTeacherName(teachers.get(i % teacherNum).getTeacherName());
                    teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                    teachingClassTeacherList.add(teachingClassTeacher);

                }
                teachingClassTeacherService.saveBatch(teachingClassTeacherList);

                String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                if (teachingClass.getFlag().equals(2)) {
                    parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                            .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                            .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                            .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType())
                            .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                            .set(ParameterSetting::getTeacherId, tIds)
                            .set(ParameterSetting::getState, 1)
                            .set(ParameterSetting::getTeacherName, tNames));

                    teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                            .eq(TeachingClass::getTaskId, taskId)
                            .in(TeachingClass::getTeachingClassId, teachingClassIds)
                            .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                            .set(TeachingClass::getState, 1));

                }else{
                    parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                            .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                            .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                            .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType())
                            .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                            .set(ParameterSetting::getTeacherId, tIds)
                            .set(ParameterSetting::getTeacherName, tNames));
                }
            }
        } else {
            List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>()
                    .eq(ClassInfo::getTaskId, taskId).in(ClassInfo::getId, assignTeachersDto.getClassInfoList()));

            List<TeachingClassTeacher> teachingClassTeacherList = new ArrayList<>();


            ParameterSetting parameterSetting = parameterSettingMapper.selectOne(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                    .eq(ParameterSetting::getGradeId, assignTeachersDto.getGradeId())
                    .eq(ParameterSetting::getCourseId, assignTeachersDto.getCourseId())
                    .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType()).eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()));

            if (ObjUtil.isNotNull(parameterSetting)) {
                teachingClassIds = new ArrayList<>(Arrays.asList(parameterSetting.getTeachingClassIdList().split(",")))
                        .stream().map(Long::valueOf).collect(Collectors.toList());
            }


            List<TeachingClass> teachingClassList = teachingClassMapper
                    .selectList(new LambdaQueryWrapper<TeachingClass>()
                            .eq(TeachingClass::getTaskId, taskId)
                            .in(TeachingClass::getTeachingClassId, teachingClassIds)
                            .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


            List<Long> teacherIds = assignTeachersDto.getTeacherIds();

            Integer teacherNum = assignTeachersDto.getTeacherIds().size();

            Integer teachingClassNum = teachingClassList.size();

            List<Long> teachingClasss = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());

            //删除之前设置的教师
            teachingClassTeacherMapper.update(null, new LambdaUpdateWrapper<TeachingClassTeacher>()
                    .in(TeachingClassTeacher::getTeachingClassId, teachingClasss)
                    .eq(TeachingClassTeacher::getTeacherType, assignTeachersDto.getHourType())
                    .set(TeachingClassTeacher::getDeleted, Deleted.YES.getCode()));


            List<Teacher> teachers = teacherMapper.getTeacherList(teacherIds);


            if (teacherNum > teachingClassNum) {
                //设置默认任课教师，班主任
                for (ClassInfo classInfo : classInfoList) {
                    Teacher teacher = teachers.stream().filter(p -> p.getBaseTeacherId().equals(classInfo.getGenderId())).findFirst().orElse(null);

                    if (teacher != null) {
                        TeachingClass teachingClass = teachingClassList.stream()
                                .filter(p -> Long.valueOf(p.getClassId()).equals(classInfo.getId())).findFirst().orElse(null);
                        if (teachingClass != null) {
                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(teachingClass.getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teacher.getTeacherId());
                            teachingClassTeacher.setTeacherName(teacher.getTeacherName());
                            teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                            teachers.remove(teacher);
                        }
                    }
                }

                //设置剩余班级
                if (CollUtil.isNotEmpty(teachers)) {
                    if (teachers.size() > teachingClassNum) {
                        for (int i = 0; i < teachers.size(); i++) {

                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();

                            teachingClassTeacher.setTeachingClassId(teachingClassList.get(i % teachingClassNum).getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teachers.get(i).getTeacherId());
                            teachingClassTeacher.setTeacherName(teachers.get(i).getTeacherName());
                            teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                        }
                    } else {
                        for (int i = 0; i < teachingClassList.size(); i++) {

                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();

                            teachingClassTeacher.setTeachingClassId(teachingClassList.get(i).getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teachers.get(i % teachers.size()).getTeacherId());
                            teachingClassTeacher.setTeacherName(teachers.get(i % teachers.size()).getTeacherName());
                            teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                        }
                    }
                }

                List<TeachingClassTeacher> collect = teachingClassTeacherList.stream().distinct().collect(Collectors.toList());

                //重新生成教学班对应教师
                teachingClassTeacherService.saveBatch(collect);
                TeachingClass teachingClass = teachingClassList.get(0);
                String tIds = collect.stream().map(TeachingClassTeacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                String tNames = collect.stream().map(TeachingClassTeacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                        .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                        .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                        .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType())
                        .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                        .set(ParameterSetting::getTeacherId, tIds)
                        .set(ParameterSetting::getTeacherName, tNames));


            } else {
                //设置默认任课教师，班主任
                for (ClassInfo classInfo : classInfoList) {
                    Teacher teacher = teachers.stream().filter(p -> p.getBaseTeacherId().equals(classInfo.getGradeId())).findFirst().orElse(null);

                    if (teacher != null) {

                        TeachingClass teachingClass = teachingClassList.stream()
                                .filter(p -> Long.valueOf(p.getClassId()).equals(classInfo.getId())).findFirst().orElse(null);
                        if (teachingClass != null) {
                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(teachingClass.getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teacher.getTeacherId());
                            teachingClassTeacher.setTeacherName(teacher.getTeacherName());
                            teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                            teachingClassList.remove(teachingClass);
                        }
                    }
                }


                //设置剩余班级
                for (int i = 0; i < teachingClassList.size(); i++) {

                    TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();

                    teachingClassTeacher.setTeachingClassId(teachingClassList.get(i).getTeachingClassId());
                    teachingClassTeacher.setTeacherId(teachers.get(i % teacherNum).getTeacherId());
                    teachingClassTeacher.setTeacherName(teachers.get(i % teacherNum).getTeacherName());
                    teachingClassTeacher.setTeacherType(assignTeachersDto.getHourType());
                    teachingClassTeacherList.add(teachingClassTeacher);
                }

                //重新生成教学班对应教师
                teachingClassTeacherService.saveBatch(teachingClassTeacherList);
                TeachingClass teachingClass = teachingClassList.get(0);
                String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                        .eq(ParameterSetting::getGradeId, teachingClass.getGradeId())
                        .eq(ParameterSetting::getCourseId, teachingClass.getCourseId())
                        .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType())
                        .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()).set(ParameterSetting::getTeacherId, tIds)
                        .set(ParameterSetting::getTeacherName, tNames));

            }
        }


        List<ParameterSetting> parameterSettingList = parameterSettingMapper.selectList(new LambdaQueryWrapper<ParameterSetting>()
                .eq(ParameterSetting::getGradeId, assignTeachersDto.getGradeId())
                .eq(ParameterSetting::getCourseId, assignTeachersDto.getCourseId())
                .eq(ParameterSetting::getFlag, 1).eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                .eq(ParameterSetting::getHourType, assignTeachersDto.getHourType()));

        List<Long> updateParameterSettingIds = new ArrayList<>();
        parameterSettingList.forEach(o -> {
            if (ObjUtil.isNotNull(o.getRoomType()) && StringUtils.isNotBlank(o.getTeacherId())) {
                updateParameterSettingIds.add(o.getId());
            }
        });

        if (CollUtil.isNotEmpty(updateParameterSettingIds)) {
            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                    .in(ParameterSetting::getTaskId, taskId)
                    .in(ParameterSetting::getId, updateParameterSettingIds)
                    .set(ParameterSetting::getState, 1));
        }


        List<TeachingClassWeek> teachingClassWeekList1 = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));
        List<TeachingClassTeacher> teachingClassTeacherList1 = teachingClassTeacherMapper
                .selectList(new LambdaQueryWrapper<TeachingClassTeacher>().in(TeachingClassTeacher::getTeachingClassId, teachingClassIds)
                        .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));

        List<Long> updateTeachingClassIds = new ArrayList<>();
        teachingClassIds.forEach(o -> {
            List<TeachingClassWeek> teachingClassWeekList2 = teachingClassWeekList1.stream().filter(p -> p.getTeachingClassId().equals(o) && !p.getHourType().equals(assignTeachersDto.getHourType())).collect(Collectors.toList());

            List<TeachingClassTeacher> teachingClassTeacherList2 = teachingClassTeacherList1.stream().filter(p -> p.getTeachingClassId().equals(o)
                    && !p.getTeacherType().equals(assignTeachersDto.getHourType()))
                    .collect(Collectors.toList());
            boolean flag = false;
            if (CollUtil.isNotEmpty(teachingClassWeekList2)) {
                List<TeachingClassWeek> collect1 = teachingClassWeekList2.stream().filter(p -> ObjUtil.isNull(p.getRoomType())).distinct().collect(Collectors.toList());
                if (!CollUtil.isEmpty(collect1)) {
                    flag = true;
                }
            }

            if (!CollUtil.isEmpty(teachingClassWeekList2) && CollUtil.isEmpty(teachingClassTeacherList2)) {
                flag = true;
            }

            if (CollUtil.isNotEmpty(teachingClassTeacherList2)) {
                Map<Integer, List<TeachingClassTeacher>> collect2 = teachingClassTeacherList2.stream().collect(Collectors.groupingBy(TeachingClassTeacher::getTeacherType));
                List<Integer> collect1 = teachingClassWeekList2.stream().filter(p -> !p.getHourType().equals(assignTeachersDto.getHourType())).map(TeachingClassWeek::getHourType)
                        .distinct().collect(Collectors.toList());
                if (collect1.size() != collect2.size()) {
                    flag = true;
                }
            }
            if (!flag) {
                updateTeachingClassIds.add(o);
            }
        });

        if (CollUtil.isNotEmpty(updateTeachingClassIds)) {
            teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                    .in(TeachingClass::getTeachingClassId, updateTeachingClassIds)
                    .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                    .set(TeachingClass::getState, 1));
        }

        return true;


    }

    /**
     * 修改场地类型
     *
     * @param taskId
     * @param courseId
     * @param roomType
     * @return
     */

    @Override
    public String modifyRoomType(Integer taskId, String gradeId, Long courseId, Integer hourType, Integer roomType) {
        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getGradeId, gradeId)
                .eq(TeachingClass::getCourseId, courseId)
                .eq(TeachingClass::getFlag, 1)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        TeachingClass teachingClass = teachingClassList.get(0);


        TaskInfo taskInfo = taskInfoService.getById(taskId);
        List<Room> roomList = roomMapper.selectList(new LambdaQueryWrapper<Room>().eq(Room::getSchoolId, taskInfo.getSchoolId())
                .eq(Room::getTerm, taskInfo.getTerm())
                .eq(Room::getDeleted, Deleted.NOT.getCode()));


        List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId)
                .distinct().collect(Collectors.toList());

        if (teachingClass.getTeachingClassType().equals(TeachingClassType.SELECT.getCode())) {
            teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                    .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                    .eq(TeachingClassWeek::getHourType, hourType)
                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode())
                    .set(TeachingClassWeek::getRoomType, roomType)
                    .set(TeachingClassWeek::getRoomId, null));

            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                    .eq(ParameterSetting::getGradeId, gradeId)
                    .eq(ParameterSetting::getCourseId, courseId)
                    .eq(ParameterSetting::getFlag, 1)
                    .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()).eq(ParameterSetting::getHourType, hourType)
                    .set(ParameterSetting::getRoomType, roomType).set(ParameterSetting::getRoomId, null));
        } else {

            if (roomType == RoomType.ClassRoom.getCode()) {

                List<TeachingClassWeek> teachingClassWeekList = teachingClassWeekMapper
                        .selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                                .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                                .eq(TeachingClassWeek::getHourType, hourType)
                                .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));
                Long roomId = teachingClass.getRoomId();
                List<Room> rooms = roomList.stream().filter(p -> p.getRoomId().equals(roomId)).collect(Collectors.toList());

                if (CollUtil.isNotEmpty(rooms)) {
                    Room room = rooms.get(0);
                    teachingClassWeekList.forEach(o -> {
                        o.setRoomId(room.getRoomId());
                        o.setRoomType(room.getRoomType());
                    });
                    parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                            .eq(ParameterSetting::getGradeId, gradeId)
                            .eq(ParameterSetting::getCourseId, courseId)
                            .eq(ParameterSetting::getFlag, 1)
                            .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()).eq(ParameterSetting::getHourType, hourType)
                            .set(ParameterSetting::getRoomType, room.getRoomType()).set(ParameterSetting::getRoomId, room.getRoomId()));
                }


                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);

                return "场地类型修改成功";
            }
            teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                    .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                    .eq(TeachingClassWeek::getHourType, hourType)
                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode())
                    .set(TeachingClassWeek::getRoomType, roomType)
                    .set(TeachingClassWeek::getRoomId, null));


            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                    .eq(ParameterSetting::getGradeId, gradeId)
                    .eq(ParameterSetting::getCourseId, courseId)
                    .eq(ParameterSetting::getFlag, 1)
                    .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()).eq(ParameterSetting::getHourType, hourType)
                    .set(ParameterSetting::getRoomType, roomType).set(ParameterSetting::getRoomId, null));


            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                    .eq(ParameterSetting::getGradeId, gradeId)
                    .eq(ParameterSetting::getCourseId, courseId)
                    .eq(ParameterSetting::getFlag, 1)
                    .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                    .eq(ParameterSetting::getHourType, hourType)
                    .set(ParameterSetting::getState, 0));


            List<ParameterSetting> parameterSettingList = parameterSettingMapper.selectList(new LambdaQueryWrapper<ParameterSetting>()
                    .eq(ParameterSetting::getGradeId, gradeId).eq(ParameterSetting::getCourseId, courseId)
                    .eq(ParameterSetting::getFlag, 1).eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()).eq(ParameterSetting::getHourType, hourType));

            List<Long> updateParameterSettingIds = new ArrayList<>();
            parameterSettingList.forEach(o -> {
                if (ObjUtil.isNotNull(o.getRoomType()) && StringUtils.isNotBlank(o.getTeacherId())) {
                    updateParameterSettingIds.add(o.getId());
                }
            });

            if (CollUtil.isNotEmpty(updateParameterSettingIds)) {
                parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                        .in(ParameterSetting::getTaskId, taskId)
                        .in(ParameterSetting::getId, updateParameterSettingIds)
                        .set(ParameterSetting::getState, 1));
            }


            List<TeachingClassWeek> teachingClassWeekList1 = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>().in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));
            List<TeachingClassTeacher> teachingClassTeacherList1 = teachingClassTeacherMapper.selectList(new LambdaQueryWrapper<TeachingClassTeacher>().in(TeachingClassTeacher::getTeachingClassId, teachingClassIds)
                    .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));

            List<Long> updateTeachingClassIds = new ArrayList<>();
            teachingClassIds.forEach(o -> {
                List<TeachingClassWeek> teachingClassWeekList2 = teachingClassWeekList1.stream().filter(p -> p.getTeachingClassId().equals(o)).collect(Collectors.toList());

                List<TeachingClassTeacher> teachingClassTeacherList2 = teachingClassTeacherList1.stream().filter(p -> p.getTeachingClassId().equals(o)).collect(Collectors.toList());
                Boolean flag = false;
                if (CollUtil.isNotEmpty(teachingClassWeekList2)) {
                    List<TeachingClassWeek> collect1 = teachingClassWeekList2.stream().filter(p -> ObjUtil.isNull(p.getRoomType())).distinct().collect(Collectors.toList());
                    if (!CollUtil.isEmpty(collect1)) {
                        flag = true;
                    }
                }

                if (CollUtil.isEmpty(teachingClassTeacherList2)) {
                    flag = true;
                }

                if (CollUtil.isNotEmpty(teachingClassTeacherList2)) {
                    Map<Integer, List<TeachingClassTeacher>> collect2 = teachingClassTeacherList2.stream().collect(Collectors.groupingBy(TeachingClassTeacher::getTeacherType));
                    List<Integer> collect1 = teachingClassWeekList2.stream().map(TeachingClassWeek::getHourType).distinct().collect(Collectors.toList());

                    if (collect1.size() != collect2.size()) {
                        flag = true;
                    }
                }
                if (!flag) {
                    updateTeachingClassIds.add(o);
                }
            });

            if (CollUtil.isNotEmpty(updateTeachingClassIds)) {
                teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                        .in(TeachingClass::getTeachingClassId, updateTeachingClassIds)
                        .eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                        .set(TeachingClass::getState, 1));
            }


        }
        return "场地类型修改成功";
    }

    /**
     * 修改周次
     *
     * @param taskId
     * @param majorId
     * @param courseId
     * @param flag
     * @param week
     * @return
     */
    @Transactional
    @Override
    public String updateWeek(Integer taskId, String gradeId, Long majorId, Long courseId, Integer hourType, Integer
            flag, String week) {
        WeekDateVo weekDateVo = taskInfoService.countWeek(taskId);

        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getGradeId, gradeId)
                .eq(TeachingClass::getMajorId, majorId).eq(TeachingClass::getCourseId, courseId)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId)
                .distinct().collect(Collectors.toList());

        List<TeachingClassWeek> teachingClassWeekList = new ArrayList<>();

        Course course = courseMapper.selectOne(new LambdaQueryWrapper<Course>().eq(Course::getTaskId, taskId).eq(Course::getCourseId, courseId));

        switch (flag) {
            case 1:
                teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                        .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                        .eq(TeachingClassWeek::getHourType, hourType)
                        .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).set(TeachingClassWeek::getWeek, week));
                teachingClassWeekList = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                        .eq(TeachingClassWeek::getTeachingClassId, teachingClassIds));

                teachingClassWeekList.forEach(o -> {
                    if (o.getHourType().equals(1)) {
                        o.setWeekNum((int) (course.getLectureHour() / weekDateVo.getWeekCount()));
                    } else if (o.getHourType().equals(2)) {
                        o.setWeekNum((int) (course.getComputerHour() / weekDateVo.getWeekCount()));
                    } else if (o.getHourType().equals(3)) {
                        o.setWeekNum((int) (course.getExperimentalHour() / weekDateVo.getWeekCount()));
                    } else if (o.getHourType().equals(4)) {
                        o.setWeekNum((int) (course.getOtherHour() / weekDateVo.getWeekCount()));
                    }
                });
                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);
                break;
            case 2:
                teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                        .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                        .eq(TeachingClassWeek::getHourType, hourType)
                        .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).set(TeachingClassWeek::getWeek, week));
                teachingClassWeekList = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                        .eq(TeachingClassWeek::getTeachingClassId, teachingClassIds));

                teachingClassWeekList.forEach(o -> {
                    if (o.getHourType().equals(1)) {
                        o.setWeekNum((int) (course.getLectureHour() / (weekDateVo.getWeekCount() / 2)));
                    } else if (o.getHourType().equals(2)) {
                        o.setWeekNum((int) (course.getComputerHour() / (weekDateVo.getWeekCount() / 2)));
                    } else if (o.getHourType().equals(3)) {
                        o.setWeekNum((int) (course.getExperimentalHour() / (weekDateVo.getWeekCount() / 2)));
                    } else if (o.getHourType().equals(4)) {
                        o.setWeekNum((int) (course.getOtherHour() / (weekDateVo.getWeekCount() / 2)));
                    }
                });

                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);
                break;
            case 3:
                teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                        .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                        .eq(TeachingClassWeek::getHourType, hourType)
                        .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).set(TeachingClassWeek::getWeek, week));
                teachingClassWeekList = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                        .eq(TeachingClassWeek::getTeachingClassId, teachingClassIds));

                teachingClassWeekList.forEach(o -> {
                    if (o.getHourType().equals(1)) {
                        o.setWeekNum((int) (course.getLectureHour() / (weekDateVo.getWeekCount() / 2)));
                    } else if (o.getHourType().equals(2)) {
                        o.setWeekNum((int) (course.getComputerHour() / (weekDateVo.getWeekCount() / 2)));
                    } else if (o.getHourType().equals(3)) {
                        o.setWeekNum((int) (course.getExperimentalHour() / (weekDateVo.getWeekCount() / 2)));
                    } else if (o.getHourType().equals(4)) {
                        o.setWeekNum((int) (course.getOtherHour() / (weekDateVo.getWeekCount() / 2)));
                    }
                });

                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);
                break;
            case 4:
                teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                        .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                        .eq(TeachingClassWeek::getHourType, hourType)
                        .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).set(TeachingClassWeek::getWeek, week));
                teachingClassWeekList = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                        .eq(TeachingClassWeek::getTeachingClassId, teachingClassIds));

                Integer oneNumber = getOneNumber(week);

                teachingClassWeekList.forEach(o -> {
                    if (o.getHourType().equals(1)) {
                        o.setWeekNum((course.getLectureHour() / oneNumber));
                    } else if (o.getHourType().equals(2)) {
                        o.setWeekNum((course.getComputerHour() / oneNumber));
                    } else if (o.getHourType().equals(3)) {
                        o.setWeekNum((course.getExperimentalHour() / oneNumber));
                    } else if (o.getHourType().equals(4)) {
                        o.setWeekNum((course.getOtherHour() / oneNumber));
                    }
                });
                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);
                break;
            default:
                log.error("flag 传入错误");
        }
        return "周次次修改成功";
    }


    private Boolean isCourseComplete(ClassDto classDto) {

        if (ObjUtil.isEmpty(classDto.getTeacherId())
                || StringUtils.isBlank(classDto.getTeacherName())) {

            return false;
        }

        if (classDto.getFlag() == 0) {

            List<WeekDto> weekDtoList = classDto.getWeekDtoList();
            for (WeekDto weekDto : weekDtoList) {
                if (ObjUtil.isEmpty(weekDto.getWeek()) || ObjUtil.isEmpty(weekDto.getWeekNum())) {

                    return false;
                }
            }
            return true;
        }
        return true;
    }


    private Integer getOneNumber(String week) {
        int count = 0;
        if (week != null && !week.isEmpty()) {
            char[] chars = week.toCharArray();
            for (char aChar : chars) {
                if (aChar == '1') {
                    count++;
                }
            }
        }
        return count;
    }


    @Override
    public List<RuleTeachingClassVo> getRuleTeachingClass(Integer taskId, Long roomId, Long teacherId, Long
            classId, Long teachingClassId) {
        List<RuleTeachingClassVo> res = baseMapper.getRuleTeachingClass(taskId, roomId, teacherId, classId, teachingClassId);
        //补充教师信息
        List<Long> teachingClassIds = res.stream().map(RuleTeachingClassVo::getTeachingClassId).collect(Collectors.toList());
        Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds)
                .stream().collect(Collectors.groupingBy(Teacher::getTeachingClassId));

        Map<Long, String> classInfoMap = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>()
                .eq(ClassInfo::getTaskId, taskId))
                .stream().collect(Collectors.toMap(ClassInfo::getId, ClassInfo::getClassName));

        res.forEach(o -> {
            //补充教师信息 单独添加，因为教师业务以后可能会变化
            List<Teacher> teachers = teachingClassToTeacher.getOrDefault(o.getTeachingClassId(), new ArrayList<>());
            if (CollUtil.isNotEmpty(teachers)) {
                //多教师版本
                teachers = teachers.stream().filter(t -> t.getTeacherType().equals(o.getHourType())).collect(Collectors.toList());
                String teacherIds = StrUtil.join(",", teachers.stream().map(Teacher::getTeacherId).collect(Collectors.toList()));
                String teacherNames = StrUtil.join(",", teachers.stream().map(Teacher::getTeacherName).collect(Collectors.toList()));
                o.setTeacherIds(teacherIds);
                o.setTeacherName(teacherNames);
            }

            if (StrUtil.isNotEmpty(o.getToClass())) {
                for (String s : o.getToClass().split(",")) {
                    String name = o.getClassName() == null ? "" : o.getClassName();
                    o.setClassName(name + "," + classInfoMap.get(Long.valueOf(s)));

                }
                o.setClassName(o.getClassName().startsWith(",") ?
                        o.getClassName().substring(1)
                        : o.getClassName());
            }

        });
        return res;
    }


    /**
     * @param page:
     * @param taskId:
     * @param classIds:
     * @Description: 行政班 教室 教学班
     * @Author: liufeng
     * @Date: 2024/1/11 13:31
     * @return:
     */
    @Override
    public PageInfo<TeachingClassWeekScheduleDto> getTeachingClassAllSchedule(IPage page, Integer
            taskId, List<Long> classIds) {

        if (CollUtil.isEmpty(classIds)) {
            return new PageInfo<>();
        }
        //term教学班
        IPage<TeachingClassWeekScheduleDto> teachingClassPage = teachingClassMapper.getTeachingClassSchedule(page, null, classIds);
        List<TeachingClassWeekScheduleDto> teachingClassList = teachingClassPage.getRecords();
        if (CollUtil.isNotEmpty(teachingClassList)) {
            List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClassWeekScheduleDto::getTeachingClassId).collect(Collectors.toList());
            //补充教师信息
            Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds)
                    .stream().collect(Collectors.groupingBy(Teacher::getTeachingClassId));

            //学生人数
            Map<Long, Integer> studentNumMap = teachingClassStudentMapper.getStudentNumber(teachingClassIds)
                    .stream().collect(Collectors.toMap(TeachingClassCourseDto::getTeachingClassId, TeachingClassCourseDto::getStudentNumber));

            //当前冲突信息
            List<ScheduleConflictInfo> cnoflictList = scheduleConflictInfoService.list(
                    new LambdaQueryWrapper<ScheduleConflictInfo>()
                            .eq(ScheduleConflictInfo::getTaskId, taskId)
                            .in(ScheduleConflictInfo::getTeachingClassId, teachingClassIds)
                            .eq(ScheduleConflictInfo::getDeleted, Deleted.NOT.getCode()));
            scheduleService.fillConflict(cnoflictList);

            Map<Long, List<ScheduleConflictInfo>> cnoflictMap = cnoflictList.stream()
                    .collect(Collectors.groupingBy(ScheduleConflictInfo::getTeachingClassId));


            //课表信息
            List<ScheduleDto> scheduleDtoList = scheduleMapper.getAllScheduleByTeachingClassIds(taskId, teachingClassIds);
            Map<Long, List<ScheduleDto>> scheduleMap = scheduleDtoList.stream().collect(Collectors.groupingBy(ScheduleDto::getTeachingClassId));

            teachingClassList.forEach(a -> {
                //多教师版本
                List<Teacher> teachers = teachingClassToTeacher.getOrDefault(a.getTeachingClassId(), ListUtil.empty());
                teachers = teachers.stream().filter(t -> Objects.equals(t.getTeacherType(), a.getHourType())).collect(Collectors.toList());
                a.setTeachers(teachers);
                //学生人数
                a.setStudentNumber(studentNumMap.getOrDefault(a.getTeachingClassId(), 0));
                //冲突
                if (CollUtil.isNotEmpty(cnoflictList)) {
                    List<ScheduleConflictInfo> scheduleConflictInfos = cnoflictMap.get(a.getTeachingClassId());
                    if (CollUtil.isNotEmpty(scheduleConflictInfos)) {
                        a.setConflicts(scheduleConflictInfos.stream()
                                .filter(o -> o.getHourType().equals(a.getHourType()))
                                .collect(Collectors.toList()));
                    }
                }
                //课表
                if (CollUtil.isNotEmpty(scheduleDtoList)) {
                    List<ScheduleDto> scheduleDtos = scheduleMap.get(a.getTeachingClassId());
                    if (CollUtil.isNotEmpty(scheduleDtos)) {
                        a.setSchedules(scheduleMap.get(a.getTeachingClassId()).stream()
                                .filter(o -> o.getHourType().equals(a.getHourType()))
                                .collect(Collectors.toList()));
                    }
                }
            });
        }
        teachingClassPage.setRecords(teachingClassList);
        return PagingUtil.formatPageResult(teachingClassPage);

    }

    /**
     * @param page:
     * @param taskId:
     * @param teachingClassTeachers:
     * @Description: 多教师  教师课表相关
     * @Author: liufeng
     * @Date: 2024/2/22 18:17
     * @return:
     */
    @Override
    public PageInfo<TeachingClassWeekScheduleDto> getTeachingClassAllSchedule
    (Page<TeachingClassWeekScheduleDto> page, Integer taskId, List<TeachingClassTeacher> teachingClassTeachers) {
        if (CollUtil.isEmpty(teachingClassTeachers)) {
            return new PageInfo<>();
        }
        //term教学班
        IPage<TeachingClassWeekScheduleDto> teachingClassPage = teachingClassMapper.getTeachingClassScheduleTeacher(page, null, teachingClassTeachers);
        List<TeachingClassWeekScheduleDto> teachingClassList = teachingClassPage.getRecords();

        if (CollUtil.isNotEmpty(teachingClassList)) {
            List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClassWeekScheduleDto::getTeachingClassId).collect(Collectors.toList());
            //补充教师信息
            Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds)
                    .stream().collect(Collectors.groupingBy(Teacher::getTeachingClassId));

            //学生人数
            Map<Long, Integer> studentNumMap = teachingClassStudentMapper.getStudentNumber(teachingClassIds)
                    .stream().collect(Collectors.toMap(TeachingClassCourseDto::getTeachingClassId, TeachingClassCourseDto::getStudentNumber));

            //当前冲突信息
            List<ScheduleConflictInfo> cnoflictList = scheduleConflictInfoService.list(
                    new LambdaQueryWrapper<ScheduleConflictInfo>()
                            .eq(ScheduleConflictInfo::getTaskId, taskId)
                            .in(ScheduleConflictInfo::getTeachingClassId, teachingClassIds)
                            .eq(ScheduleConflictInfo::getDeleted, Deleted.NOT.getCode()));

            Map<Long, List<ScheduleConflictInfo>> cnoflictMap = cnoflictList.stream()
                    .collect(Collectors.groupingBy(ScheduleConflictInfo::getTeachingClassId));


            //课表信息
            List<ScheduleDto> scheduleDtoList = scheduleMapper.getAllScheduleByTeachingClassIds(taskId, teachingClassIds);
            Map<Long, List<ScheduleDto>> scheduleMap = scheduleDtoList.stream().collect(Collectors.groupingBy(ScheduleDto::getTeachingClassId));

            teachingClassList.forEach(a -> {
                //多教师版本
                List<Teacher> teachers = teachingClassToTeacher.getOrDefault(a.getTeachingClassId(), ListUtil.empty());
                teachers = teachers.stream().filter(t -> Objects.equals(t.getTeacherType(), a.getHourType())).collect(Collectors.toList());
                a.setTeachers(teachers);
                //学生人数
                a.setStudentNumber(studentNumMap.getOrDefault(a.getTeachingClassId(), 0));
                //冲突
                if (CollUtil.isNotEmpty(cnoflictList)) {
                    List<ScheduleConflictInfo> scheduleConflictInfos = cnoflictMap.get(a.getTeachingClassId());
                    if (CollUtil.isNotEmpty(scheduleConflictInfos)) {
                        a.setConflicts(scheduleConflictInfos.stream()
                                .filter(o -> o.getHourType().equals(a.getHourType()))
                                .collect(Collectors.toList()));
                    }
                }
                //课表
                if (CollUtil.isNotEmpty(scheduleDtoList)) {
                    List<ScheduleDto> scheduleDtos = scheduleMap.get(a.getTeachingClassId());
                    if (CollUtil.isNotEmpty(scheduleDtos)) {
                        a.setSchedules(scheduleMap.get(a.getTeachingClassId()).stream()
                                .filter(o -> o.getHourType().equals(a.getHourType()))
                                .collect(Collectors.toList()));
                    }
                }
            });
        }
        teachingClassPage.setRecords(teachingClassList);
        return PagingUtil.formatPageResult(teachingClassPage);
    }

    /**
     * @param page:
     * @param taskId:
     * @param classIds:
     * @Description: 导出课表 已安排课时的
     * @Author: liufeng
     * @Date: 2023/12/28 15:38
     * @return:
     */
    @Override
    public PageInfo<TeachingClassWeekScheduleDto> getTeachingClassSchedule(IPage page, Integer
            taskId, List<Long> classIds, Long roomId) {

        //教学班
        IPage<TeachingClassWeekScheduleDto> teachingClassPage = teachingClassMapper.getTeachingClassSchedule(page, taskId, classIds);
        List<TeachingClassWeekScheduleDto> teachingClassList = teachingClassPage.getRecords();
        if (CollUtil.isNotEmpty(teachingClassList)) {
            List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClassWeekScheduleDto::getTeachingClassId).collect(Collectors.toList());
            //补充教师信息
            Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds)
                    .stream().collect(Collectors.groupingBy(Teacher::getTeachingClassId));

            //课表信息
            List<ScheduleDto> scheduleDtoList = scheduleMapper.getScheduleByTeachingClassIds(taskId, teachingClassIds, roomId);
            Map<Long, List<ScheduleDto>> scheduleMap = scheduleDtoList.stream().collect(Collectors.groupingBy(ScheduleDto::getTeachingClassId));

            teachingClassList.forEach(a -> {
                //多教师版本
                List<Teacher> teacher = teachingClassToTeacher.getOrDefault(a.getTeachingClassId(), ListUtil.empty());
                teacher = teacher.stream().filter(t -> Objects.equals(t.getTeacherType(), a.getHourType())).collect(Collectors.toList());

                a.setTeachers(teacher);
                //课表
                if (CollUtil.isNotEmpty(scheduleMap.get(a.getTeachingClassId()))) {
                    a.setSchedules(scheduleMap.get(a.getTeachingClassId()).stream()
                            .filter(o -> o.getHourType().equals(a.getHourType()))
                            .collect(Collectors.toList()));
                } else {
                    a.setSchedules(new ArrayList<>());
                }
            });
        }
        teachingClassPage.setRecords(teachingClassList);
        return PagingUtil.formatPageResult(teachingClassPage);

    }

    @Override
    public PageInfo<TeachingClassCourseDto> getSelectionTeachingClass(Page<TeachingClassCourseDto> page, Integer
            taskId, Integer handleState, Long courseId, String keyWord, Integer minClassNum) {


        IPage<TeachingClassCourseDto> teachingClassByConditions = teachingClassMapper.getSelectionTeachingClass(page, taskId, handleState, courseId, keyWord, minClassNum);

        if (handleState.equals(3) || handleState.equals(2)) {

            List<TeachingClassCourseDto> records = teachingClassByConditions.getRecords();
            List<TeachingClassCourseDto> collect = records.stream().filter(p -> !p.getIsEnable().equals(4)).collect(Collectors.toList());
            teachingClassByConditions.setRecords(collect);
        }

        //填充其他数据
        List<TeachingClassCourseDto> records = teachingClassByConditions.getRecords();


        if (CollUtil.isNotEmpty(records)) {
            List<Long> teachingClassIds = records.stream().map(TeachingClassCourseDto::getTeachingClassId).distinct().collect(Collectors.toList());
            records.forEach(o -> {
                o.setMinClassNum(minClassNum);
            });
            if (handleState.equals(2) || handleState.equals(3) || handleState.equals(4)) {
                records.forEach(o -> {
                    o.setFlag(handleState);
                });
            }

            if (ObjUtil.isNull(handleState) || handleState == 5) {
                for (TeachingClassCourseDto record : records) {
                    if (record.getIsEnable().equals(4)) {
                        record.setFlag(4);
                        continue;
                    } else {

                        if (record.getStudentNumber() < minClassNum) {
                            record.setFlag(3);
                        } else {
                            record.setFlag(2);
                        }
                    }
                }
            }
            Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds).stream()
                    .collect(Collectors.groupingBy(Teacher::getTeachingClassId));
            records.forEach(a -> {
                List<Teacher> teacherList = teachingClassToTeacher.get(a.getTeachingClassId());
                List<Teacher> teacherList1 = new ArrayList<>();
                Set<String> baseTeacherId = new HashSet<>();
                if (CollUtil.isNotEmpty(teacherList)) {
                    teacherList.forEach(o -> {
                        if (!baseTeacherId.contains(o.getBaseTeacherId())) {
                            baseTeacherId.add(o.getBaseTeacherId());
                            teacherList1.add(o);
                        }
                    });
                }
                a.setTeachers(teacherList1);
            });
        }

        teachingClassByConditions.setRecords(records);
        return PagingUtil.formatPageResult(teachingClassByConditions);

    }

    /**
     * 批量修改教学班状态
     *
     * @param teachingClassIds
     * @param isEnable
     */
    @Override
    public void updateTeachingClassEnable(List<Long> teachingClassIds, Integer isEnable) {
        LambdaUpdateWrapper<TeachingClass> updateWrapper = new LambdaUpdateWrapper<TeachingClass>()
                .in(TeachingClass::getTeachingClassId, teachingClassIds).eq(TeachingClass::getDeleted, Deleted.NOT.getCode())
                .set(TeachingClass::getIsEnable, isEnable);
        this.update(updateWrapper);
        //在线选课 取消开班 发送消息
        if (isEnable == 4) {
            // 发送消息
            Integer taskId = Integer.parseInt(request.getHeader("taskId"));
            String userId = request.getHeader("userId");
            String userName = request.getHeader("userName");
            String authorization = request.getHeader("Authorization");
            yunService.sendSelectCourseCancelMsg(teachingClassIds, taskId, userId, userName, authorization);
        }
    }

    @Override
    public PublishStatisticsPre preStatistics(Integer taskId, Integer teachingClassType, Integer minClassNum) {
        PublishStatisticsPre publishStatisticsPre = new PublishStatisticsPre();
        List<TeachingClassCourseDto> list = teachingClassMapper.getSelectStatistic(taskId, teachingClassType);
        int releaseNumber = list.size();
        long notReachedNumber = 0;
        long cancelNumber = 0;
        if (teachingClassType == 1) {
            cancelNumber = list.stream().filter(a -> a.getIsEnable().equals(4)).count();
//            notReachedNumber = list.size()-cancelNumber;
        }

        List<Long> courseIds = list.stream().map(TeachingClassCourseDto::getCourseId).distinct().collect(Collectors.toList());

        long studentRetakeNum = 0;
        long enableStudentNum = 0;


        Integer selectStudent = teachingClassMapper.getSelectStudent(taskId, teachingClassType);
        int sum = list.stream().mapToInt(TeachingClassCourseDto::getClassNum).sum();


        double capacity = (double) selectStudent / (sum != 0 ? sum : 1) * 100;

        if(CollUtil.isNotEmpty(courseIds)){

            List<Course> courseList = courseMapper.selectList(new LambdaQueryWrapper<Course>().eq(Course::getTaskId, taskId).in(Course::getCourseId, courseIds).eq(Course::getDeleted, Deleted.NOT.getCode()));

            List<String> baseCourseIds = courseList.stream().map(Course::getBaseCourseId).distinct().collect(Collectors.toList());

            TaskInfo taskInfo = taskInfoService.getById(taskId);

            if(CollUtil.isNotEmpty(baseCourseIds)){
                List<StudentRetake> list1 = studentRetakeService.lambdaQuery().eq(StudentRetake::getTaskId, taskId)
                        .eq(StudentRetake::getSchoolId, taskInfo.getSchoolId()).in(StudentRetake::getBaseCourseId,baseCourseIds)
                        .eq(StudentRetake::getTerm, taskInfo.getTerm()).list();


                Map<String, List<StudentRetake>> studentMap = list1.stream().collect(Collectors.groupingBy(StudentRetake::getBaseStudentId));
                studentRetakeNum = studentMap.size();

                List<StudentRetake> enableStudent = list1.stream().filter(p -> p.getIsAllocation().equals(1)).collect(Collectors.toList());
                Map<String, List<StudentRetake>> enableStudentMap = enableStudent.stream().collect(Collectors.groupingBy(StudentRetake::getBaseStudentId));
                enableStudentNum = enableStudentMap.size();

            }
        }

        //统计学生数量并去重 or 不去重
        publishStatisticsPre.setReleaseNumber(releaseNumber)
                .setStudentRetake(studentRetakeNum)
                .setStudentRetakeIsAllocation(enableStudentNum)
//                .setNotReachedNumber(notReachedNumber)
                .setCancelTeachingClassNum(cancelNumber)
                .setStandardNumber(releaseNumber - cancelNumber)
                .setCapacity(capacity)
                .setStudentNumber(selectStudent);
        return publishStatisticsPre;
    }

    @Override
    public RelatedNum getRelatedClassInfo(Integer taskId, String schoolId, String term) {
        RelatedNum relatedNum = new RelatedNum();
        List<StudentRetake> studentRetakeList = studentRetakeService.lambdaQuery()
                .eq(StudentRetake::getTaskId, taskId).eq(StudentRetake::getSchoolId, schoolId)
                .eq(StudentRetake::getTerm, term)
                .eq(StudentRetake::getDeleted, Deleted.NOT.getCode())
                .list();

        Map<String, List<StudentRetake>> studentRetakeMap = studentRetakeList.stream()
                .collect(Collectors.groupingBy(StudentRetake::getBaseStudentId));

        relatedNum.setTotalRelatedNum(studentRetakeMap.size());
        int count = 0;
        for (Map.Entry<String, List<StudentRetake>> entry : studentRetakeMap.entrySet()) {
            for (StudentRetake studentRetake : entry.getValue()) {
                if (studentRetake.getIsAllocation() != 1) {
                    count++;
                    break;
                }
            }
        }
        relatedNum.setRealRelatedNum(count);

        return relatedNum;
    }

    @Override
    public PublishDeselectStatistic getDeselectStatistic(Integer taskId) {
        PublishDeselectStatistic publishDeselectStatistic = new PublishDeselectStatistic();
        List<TeachingClassCourseDto> list = teachingClassMapper.getDeselectStatistic(taskId);
        int totalNumber = list.size();
        long deselectNumber = list.stream().filter(a -> a.getStudentNumber() > 0).count();
        //统计学生数量并去重 or 不去重
        int studentNumber = list.stream().mapToInt(TeachingClassCourseDto::getStudentNumber).sum();
        publishDeselectStatistic.setTotalNumber(totalNumber)
                .setDeselectNumber(deselectNumber)
                .setStudentNumber(studentNumber);
        return publishDeselectStatistic;
    }

    @Override
    public List<TeachingClassStudent> updateStudent(Long teachingClassId, List<Long> studentIds) {
        List<TeachingClassStudent> teachingClassStudentList = new ArrayList<>();
        teachingClassStudentMapper.update(null, new LambdaUpdateWrapper<TeachingClassStudent>()
                .eq(TeachingClassStudent::getTeachingClassId, teachingClassId).set(TeachingClassStudent::getDeleted, Deleted.YES.getCode()));
        if (CollUtil.isNotEmpty(studentIds)) {
            studentIds.forEach(studentId -> teachingClassStudentList.add(new TeachingClassStudent()
                    .setTeachingClassId(teachingClassId)
                    .setStudentId(studentId)
                    .setDeleted(Deleted.NOT.getCode())
                    .setFlag(1)));
        }

        //批量插入教学班学生，大数据批量插入
        Consumer<List<TeachingClassStudent>> studentConsumer = o -> teachingClassStudentMapper.addBatch(o);
        BatchInsert.batchSplitInsert(teachingClassStudentList, studentConsumer);
        return teachingClassStudentList;

    }

    @Override
    public List<TeachingClass> getTeachingClassIdsByRoomId(Integer taskId, Long roomId) {
        return baseMapper.selectListByRoomId(taskId, roomId);
    }

    @Override
    public PageInfo<TeachingClassCourseDto> getReleaseSelectionTeachingClass
            (Page<TeachingClassCourseDto> page, Integer taskId, Integer handleState, String gradeId, Long majorId, String
                    keyWord, Integer minClassNum) {
        IPage<TeachingClassCourseDto> teachingClassByConditions = teachingClassMapper.getReleaseSelectionTeachingClass(page, taskId, handleState, gradeId, majorId, keyWord, minClassNum);
        //填充其他数据
        List<TeachingClassCourseDto> records = teachingClassByConditions.getRecords();


        if (CollUtil.isNotEmpty(records)) {
            List<Long> teachingClassIds = records.stream().map(TeachingClassCourseDto::getTeachingClassId).distinct().collect(Collectors.toList());
            records.forEach(o -> {
                o.setMinClassNum(minClassNum);
            });
            if (handleState.equals(2) || handleState.equals(3) || handleState.equals(4) || handleState.equals(6)) {


                records.forEach(o -> {
                    o.setFlag(handleState);
                });
            }

            if (ObjUtil.isNull(handleState) || handleState == 5) {
                for (TeachingClassCourseDto record : records) {
                    if (record.getIsEnable().equals(4)) {
                        record.setFlag(4);
                    } else if (record.getIsEnable().equals(6)) {
                        record.setFlag(6);
                    } else {
                        if (record.getStudentNumber() < minClassNum) {
                            record.setFlag(2);
                        } else {
                            record.setFlag(2);
                        }
                    }
                }
            }
            Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds).stream()
                    .collect(Collectors.groupingBy(Teacher::getTeachingClassId));
            records.forEach(a -> {

                List<Long> teacherList = new ArrayList<>();
                List<Teacher> teacherList1 = teachingClassToTeacher.get(a.getTeachingClassId());
                List<Teacher> collect = new ArrayList<>();
                if (CollUtil.isNotEmpty(teacherList1)) {
                    teacherList1.forEach(o -> {
                        if (!teacherList.contains(o.getTeacherId())) {
                            teacherList.add(o.getTeacherId());
                            collect.add(o);
                        }
                    });
                }
                a.setTeachers(collect);
            });
        }

        teachingClassByConditions.setRecords(records);
        return PagingUtil.formatPageResult(teachingClassByConditions);
    }

    @Override
    public void csToExcel(HttpServletResponse response, Integer taskId, Integer handleState, String gradeId, String
            gradeName, Long majorId, String majorName, String keyWord, Integer minClassNum, Integer currentPage, Integer
                                  pageSize) {

        TaskInfo taskInfo = taskInfoService.getById(taskId);

        String title = "{}选课教学班信息导出  学期：{} 年级：{}    状态：{}";
        String format = StrUtil.format(title, taskInfo.getSchoolName(), taskInfo.getTermName()
                , StringUtils.isNotBlank(gradeName) ? gradeName : "全部年级",
                handleState == null ? "全部状态" :
                        (handleState == 2 ? "正常开班" :
                                (handleState == 4 ? "取消开班" : handleState == 5 ? "全部开班" :
                                        (handleState == 6 ? "拆班新增" : "未知状态"))));


        Page<TeachingClassCourseDto> page = new Page<>(currentPage, pageSize);
        page.setOptimizeCountSql(false);


        PageInfo<TeachingClassCourseDto> releaseSelectionTeachingClass = this.getReleaseSelectionTeachingClass(page, taskId, handleState, gradeId, majorId, keyWord, minClassNum);

        List<TeachingClassCourseDto> list = releaseSelectionTeachingClass.getList();
        List<ReleaseSelectionToExcel> releaseSelectionToExcelList = new ArrayList<>();

        list.forEach(o -> {
            ReleaseSelectionToExcel releaseSelectionToExcel = new ReleaseSelectionToExcel();

            releaseSelectionToExcel.setCourseName(o.getCourseName());
            releaseSelectionToExcel.setTeachingClassName(o.getTeachingClassName());
            List<Teacher> teachers = o.getTeachers();

            if (CollUtil.isNotEmpty(teachers)) {
                String teacherNames = teachers.stream().map(Teacher::getTeacherName).distinct().collect(Collectors.joining(","));
                releaseSelectionToExcel.setTeacherName(teacherNames);
            }

            releaseSelectionToExcel.setCampusName(o.getCampusName());
            releaseSelectionToExcel.setGradeName(o.getGradeName());
            releaseSelectionToExcel.setClassNum(o.getClassNum());
            releaseSelectionToExcel.setMinimum(o.getMinClassNum());
            releaseSelectionToExcel.setSelectNum(o.getStudentNumber());
            releaseSelectionToExcel.setIsEnable(o.getFlag() == null ? "全部状态" :
                    (o.getFlag() == 2 ? "正常开班" :
                            (o.getFlag() == 4 ? "取消开班" :
                                    (o.getFlag() == 3 ? "取消开班" :
                                            o.getFlag() == 6 ? "拆班新增" : "未知状态"))));

            releaseSelectionToExcelList.add(releaseSelectionToExcel);
        });


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));


        MyExcelUtils.exportExcel(releaseSelectionToExcelList,
                format,
                "小组信息",
                ReleaseSelectionToExcel.class,
                "发布选课信息导出" + time + ".xls", response);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String recoverSelection(Integer taskId, RecoverSelectionDto recoverSelectionDto) {

        //删除之前的教学班

        teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .in(TeachingClass::getTeachingClassId, recoverSelectionDto.getTeachingClassIds())
                .set(TeachingClass::getDeleted, Deleted.YES.getCode()));


        teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                .in(TeachingClassWeek::getTeachingClassId, recoverSelectionDto.getTeachingClassIds()).set(TeachingClassWeek::getDeleted, Deleted.YES.getCode()));


        teachingClassTeacherMapper.update(null, new LambdaUpdateWrapper<TeachingClassTeacher>()
                .in(TeachingClassTeacher::getTeachingClassId, recoverSelectionDto.getTeachingClassIds()).set(TeachingClassTeacher::getDeleted, Deleted.YES.getCode()));

        teachingClassStudentMapper.update(null, new LambdaUpdateWrapper<TeachingClassStudent>()
                .in(TeachingClassStudent::getTeachingClassId, recoverSelectionDto.getTeachingClassIds()).set(TeachingClassStudent::getDeleted, Deleted.YES.getCode()));


        TaskInfo taskInfo = taskInfoService.getById(taskId);
        List<Teacher> teacherList = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().eq(Teacher::getSchoolId, taskInfo.getSchoolId()).eq(Teacher::getTerm, taskInfo.getTerm()));


        List<ParameterSetting> parameterSettingList = parameterSettingMapper.selectList(new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                .eq(ParameterSetting::getGradeId, recoverSelectionDto.getGradeId())
                .eq(ParameterSetting::getCourseId, recoverSelectionDto.getCourseId()));


        int state = 0;
        int sum = parameterSettingList.stream().mapToInt(ParameterSetting::getState).sum();
        state = sum != parameterSettingList.size() ? 0 : 1;


        List<String> collect1 = recoverSelectionDto.getClassInfoList().stream().map(String::valueOf).collect(Collectors.toList());

        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getCourseId, recoverSelectionDto.getCourseId())
                .in(TeachingClass::getClassId, collect1).isNull(TeachingClass::getUniqueShiftSign));


        List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());

        String collect = teachingClassIds.stream().map(String::valueOf).collect(Collectors.joining(","));


        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                .eq(ParameterSetting::getGradeId, recoverSelectionDto.getGradeId())
                .eq(ParameterSetting::getCourseId, recoverSelectionDto.getCourseId())
                .set(ParameterSetting::getTeachingClassIdList, collect));


        teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .in(TeachingClass::getTeachingClassId, teachingClassIds)
                .set(TeachingClass::getTeachingClassType, TeachingClassType.NOSELECT.getCode())
                .set(TeachingClass::getState, state)
                .set(TeachingClass::getDeleted, Deleted.NOT.getCode()));


        teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>()
                .in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                .set(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));

        teachingClassStudentMapper.update(null, new LambdaUpdateWrapper<TeachingClassStudent>()
                .in(TeachingClassStudent::getTeachingClassId, teachingClassIds)
                .set(TeachingClassStudent::getDeleted, Deleted.NOT.getCode()));


        teachingClassTeacherMapper.update(null, new LambdaUpdateWrapper<TeachingClassTeacher>()
                .in(TeachingClassTeacher::getTeachingClassId, teachingClassIds)
                .set(TeachingClassTeacher::getDeleted, Deleted.YES.getCode()));


        if (CollUtil.isNotEmpty(parameterSettingList)) {

            parameterSettingList.forEach(o -> {

                if (StringUtils.isNotBlank(o.getTeacherId())) {
                    List<TeachingClassTeacher> teachingClassTeacherList1 = new ArrayList<>();
                    List<String> strings = Arrays.asList(o.getTeacherId().split(","));
                    List<Long> collect3 = strings.stream().map(Long::valueOf).collect(Collectors.toList());

                    List<Long> collect2 = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());
                    AssignTeachersDto assignTeachersDto = new AssignTeachersDto();
                    assignTeachersDto.setClassInfoList(recoverSelectionDto.getClassInfoList());
                    assignTeachersDto.setIsChooseCourse(1);
                    assignTeachersDto.setHourType(o.getHourType());
                    assignTeachersDto.setTeacherIds(collect3);

                    Integer teacherNum = assignTeachersDto.getTeacherIds().size();

                    Integer teachingClassNum = teachingClassList.size();

                    TeachingClass teachingClass1 = teachingClassList.get(0);


                    //开始设置教师
                    List<Teacher> teachers = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>()
                            .in(Teacher::getTeacherId, assignTeachersDto.getTeacherIds())
                            .eq(Teacher::getDeleted, Deleted.NOT.getCode()));


                    //  如果教师数量大于教学班数量
                    if (teacherNum > teachingClassNum) {
                        for (int i = 0; i < teachers.size(); i++) {
                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(teachingClassList.get(i % teachingClassNum).getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teachers.get(i).getTeacherId());
                            teachingClassTeacher.setTeacherName(teachers.get(i).getTeacherName());
                            teachingClassTeacher.setTeacherType(o.getHourType());
                            teachingClassTeacherList1.add(teachingClassTeacher);
                        }


                        teachingClassTeacherService.saveBatch(teachingClassTeacherList1);


                        teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>()
                                .in(TeachingClass::getTeachingClassId, teachingClassIds)
                                .set(TeachingClass::getState, 1));


                        String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                        String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                                .eq(ParameterSetting::getGradeId, teachingClass1.getGradeId())
                                .eq(ParameterSetting::getCourseId, teachingClass1.getCourseId())
                                .eq(ParameterSetting::getHourType, o.getHourType())
                                .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                                .set(ParameterSetting::getTeacherId, tIds)
                                .set(ParameterSetting::getTeacherName, tNames)
                                .set(ParameterSetting::getState, 1));
                    } else {
                        for (int i = 0; i < teachingClassList.size(); i++) {

                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(teachingClassList.get(i).getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teachers.get((i % teacherNum)).getTeacherId());
                            teachingClassTeacher.setTeacherName(teachers.get(i % teacherNum).getTeacherName());
                            teachingClassTeacher.setTeacherType(o.getHourType());
                            teachingClassTeacherList1.add(teachingClassTeacher);

                        }
                        teachingClassTeacherService.saveBatch(teachingClassTeacherList1);
                        teachingClassMapper.update(null, new LambdaUpdateWrapper<TeachingClass>().in(TeachingClass::getTeachingClassId, teachingClassIds).set(TeachingClass::getState, 1));

                        String tIds = teachers.stream().map(Teacher::getTeacherId).map(String::valueOf).distinct().collect(Collectors.joining(","));
                        String tNames = teachers.stream().map(Teacher::getTeacherName).map(String::valueOf).distinct().collect(Collectors.joining(","));

                        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                                .eq(ParameterSetting::getGradeId, teachingClass1.getGradeId())
                                .eq(ParameterSetting::getCourseId, teachingClass1.getCourseId())
                                .eq(ParameterSetting::getHourType, o.getHourType())
                                .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())
                                .set(ParameterSetting::getTeacherId, tIds)
                                .set(ParameterSetting::getTeacherName, tNames)
                                .set(ParameterSetting::getState, 1));
                    }

                }
            });
        }


        return "选课信息已恢复";


    }

    @Override
    public String allTeachingClassToExcel(Integer taskId, String importMode) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteClassRelated(List<Integer> taskIds) {
        List<Long> teachingClassIds = teachingClassMapper.getClassIdsByTaskId(taskIds);
        if (CollUtil.isNotEmpty(teachingClassIds)) {
            teachingClassStudentMapper.delete(new LambdaQueryWrapper<TeachingClassStudent>().in(TeachingClassStudent::getTeachingClassId, teachingClassIds));
            teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>().in(TeachingClassTeacher::getTeachingClassId, teachingClassIds));
            teachingClassWeekService.remove(new LambdaQueryWrapper<TeachingClassWeek>().in(TeachingClassWeek::getTeachingClassId, teachingClassIds));
            this.remove(new LambdaQueryWrapper<TeachingClass>().in(TeachingClass::getTaskId, taskIds));
        }
    }

    @Override
    public TeachingClassDtoVo getTeachingClassListV2(Integer taskId, String gradeId, Integer courseType, String
            keyword, Integer currentPage, Integer pageSize, Integer state) {
        TeachingClassDtoVo teachingClassDtoVo = new TeachingClassDtoVo();


        List<TeachingClassDto> teachingClassDtos = new ArrayList<>();


        List<ParameterSetting> parameterSettingList = parameterSettingMapper.selectList(
                new LambdaQueryWrapper<ParameterSetting>()
                        .eq(ParameterSetting::getTaskId, taskId)
                        .eq(StringUtils.isNotBlank(gradeId), ParameterSetting::getGradeId, gradeId)
                        .eq(ObjUtil.isNotNull(courseType), ParameterSetting::getFlag, courseType)
                        .eq(ObjUtil.isNotNull(state), ParameterSetting::getState, state)
                        .and(StrUtil.isNotBlank(keyword), wrapper -> wrapper.like(ParameterSetting::getCourseName, keyword))
                        .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode()));


        Page<ParameterSetting> page = new Page<>(currentPage, pageSize);

        page.setOptimizeCountSql(false);


        IPage<ParameterSetting> settingIPage = parameterSettingMapper.selectPage(page, new LambdaQueryWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)

                .eq(StringUtils.isNotBlank(gradeId), ParameterSetting::getGradeId, gradeId)

                .eq(ObjUtil.isNotNull(courseType), ParameterSetting::getFlag, courseType)

                .eq(ParameterSetting::getDeleted, Deleted.NOT.getCode())

                .eq(ObjUtil.isNotNull(state), ParameterSetting::getState, state)

                .and(StrUtil.isNotBlank(keyword), wrapper -> wrapper.like(ParameterSetting::getCourseName, keyword))

                .orderByAsc(ParameterSetting::getGradeName).orderByAsc(ParameterSetting::getMajorName)

                .orderByAsc(ParameterSetting::getCourseName).orderByAsc(ParameterSetting::getHourType));


        List<ParameterSetting> records = settingIPage.getRecords();

        List<Course> courseList = courseMapper.getCourseList(taskId);

        List<Segment> segmentList = segmentMapper.getSegmentList(taskId);

        Map<String, List<ParameterSetting>> gradeMap = records.stream().collect(Collectors.groupingBy(ParameterSetting::getGradeId));


        gradeMap.forEach((key, value) -> {

            TeachingClassDto teachingClassDto = new TeachingClassDto();

            teachingClassDto.setGradeId(key);

            ParameterSetting gradeTeaching = value.get(0);

            teachingClassDto.setGradeName(gradeTeaching.getGradeName());

            List<ClassDto> classDtoList = new ArrayList<>();

            List<ParameterSetting> collect1 = value.stream().filter(p -> p.getFlag().equals(1)).collect(Collectors.toList());
            List<ParameterSetting> collect2 = value.stream().filter(p -> p.getFlag().equals(2)).collect(Collectors.toList());

            Map<Long, List<ParameterSetting>> courseMap = collect1.stream().collect(Collectors.groupingBy(ParameterSetting::getCourseId));
            Map<Long, List<ParameterSetting>> segmentMap = collect2.stream().collect(Collectors.groupingBy(ParameterSetting::getCourseId));

            courseMap.forEach((c, cm) -> {
                ParameterSetting parameterSetting = cm.get(0);
                Course course = courseList.stream().filter(p -> p.getCourseId().equals(c)).findFirst().orElse(null);
                if (course != null) {
                    ClassDto classDto = new ClassDto();
                    classDto.setCourseId(c);
                    classDto.setCourseType(course.getCourseType());
                    classDto.setCourseTypeId(course.getCourseTypeId());
                    classDto.setCourseName(course.getCourseName());
                    classDto.setCourseNature(course.getCourseNature());
                    classDto.setFlag(1);
                    classDto.setState(parameterSetting.getState());
                    classDto.setIsEnable(parameterSetting.getIsEnable());
                    classDto.setIsChooseCourse(parameterSetting.getTeachingClassType());
                    List<Long> classIds = Arrays.stream(parameterSetting.getClassIdList().split(",")).map(Long::valueOf).distinct().collect(Collectors.toList());
                    classDto.setClassIds(classIds);
                    List<Long> teachingClassIds = Arrays.stream(parameterSetting.getTeachingClassIdList().split(",")).map(Long::valueOf).distinct().collect(Collectors.toList());
                    classDto.setTeachingClassIds(teachingClassIds);

                    classDto.setCredit(course.getCredit());

                    List<WeekDto> weekDtos = new ArrayList<>();

                    cm.forEach(o -> {

                        List<String> teacherIds = new ArrayList<>();

                        List<String> teacherNames = new ArrayList<>();

                        String teacherIdsString = "";

                        String teacherNameString = "";

                        if (StringUtils.isNotBlank(o.getTeacherId())) {

                            teacherIds = new ArrayList<>(Arrays.asList(o.getTeacherId().split(",")));

                            teacherIdsString = String.join("、", teacherIds);
                        }

                        if (StringUtils.isNotBlank(o.getTeacherName())) {

                            teacherNames = new ArrayList<>(Arrays.asList(o.getTeacherName().split(",")));
                            teacherNameString = String.join("、", teacherNames);

                        }
                        WeekDto weekDto = new WeekDto();

                        weekDto.setAssessmentId(o.getAssessmentMethodId());

                        weekDto.setAssessmentName(o.getAssessmentMethod());

                        weekDto.setHourType(o.getHourType());

                        weekDto.setWeek(o.getWeek());

                        Integer weekNum = getOneNumber(o.getWeek());

                        weekDto.setTotalStudyHour(weekNum * o.getWeekNum());

                        weekDto.setRoomType(o.getRoomType());

                        weekDto.setRoomId(o.getRoomId());

                        weekDto.setTeacherId(teacherIdsString);

                        weekDto.setTeacherName(teacherNameString);

                        weekDto.setRoomTypeName(GlobalConstant.roomTypeMap.get(o.getRoomType()));

                        weekDto.setWeekNum(o.getWeekNum());

                        weekDto.setSign(o.getSign());

                        weekDto.setStartWeek(o.getStartWeek());

                        weekDto.setEndWeek(o.getEndWeek());

                        weekDto.setConnectNumber(o.getConnectNumber());

                        weekDto.setConnectSection(o.getConnectSection());

                        weekDtos.add(weekDto);


                    });

                    List<WeekDto> collect = weekDtos.stream().sorted(Comparator.comparing(WeekDto::getHourType)).collect(Collectors.toList());

                    classDto.setWeekDtoList(collect);

                    classDtoList.add(classDto);

                }

            });

            segmentMap.forEach((c, cm) -> {
                ParameterSetting parameterSetting = cm.get(0);
                Segment segment = segmentList.stream().filter(p -> p.getSegmentId().equals(c)).findFirst().orElse(null);
                if (segment != null) {
                    ClassDto classDto = new ClassDto();
                    classDto.setCourseId(c);
                    classDto.setCourseTypeId(segment.getSegmentTypeId());
                    classDto.setCourseType(segment.getSegmentType());
                    classDto.setCourseName(segment.getSegmentName());
                    classDto.setFlag(2);
                    classDto.setIsEnable(parameterSetting.getIsEnable());

                    List<Long> classIds = Arrays.stream(parameterSetting.getClassIdList().split(",")).map(Long::valueOf).distinct().collect(Collectors.toList());
                    classDto.setClassIds(classIds);
                    classDto.setState(parameterSetting.getState());
                    List<Long> teachingClassIds = Arrays.stream(parameterSetting.getTeachingClassIdList().split(",")).map(Long::valueOf).distinct().collect(Collectors.toList());
                    classDto.setTeachingClassIds(teachingClassIds);
                    classDto.setCredit(segment.getCredit());
                    List<WeekDto> weekDtos = new ArrayList<>();

                    cm.forEach(o -> {
                        List<String> teacherIds = new ArrayList<>();
                        List<String> teacherNames = new ArrayList<>();
                        String teacherIdsString = "";
                        String teacherNameString = "";
                        if (StringUtils.isNotBlank(o.getTeacherId())) {
                            teacherIds = new ArrayList<>(Arrays.asList(o.getTeacherId().split(",")));
                            teacherIds = teacherIds.stream().distinct().collect(Collectors.toList());
                            teacherIdsString = String.join("、", teacherIds);
                        }
                        if (StringUtils.isNotBlank(o.getTeacherName())) {
                            teacherNames = new ArrayList<>(Arrays.asList(o.getTeacherName().split(",")));
                            teacherNames = teacherNames.stream().distinct().collect(Collectors.toList());
                            teacherNameString = String.join("、", teacherNames);
                        }
                        WeekDto weekDto = new WeekDto();

                        weekDto.setTeacherId(teacherIdsString);

                        weekDto.setTeacherName(teacherNameString);

                        weekDto.setWeek(o.getWeek());

                        weekDto.setSign(o.getSign());

                        weekDto.setStartWeek(o.getStartWeek());

                        weekDto.setEndWeek(o.getEndWeek());

                        weekDtos.add(weekDto);


                    });

                    List<WeekDto> collect = weekDtos.stream().sorted(Comparator.comparing(WeekDto::getHourType)).collect(Collectors.toList());

                    classDto.setWeekDtoList(collect);

                    classDtoList.add(classDto);

                }

            });

            List<ClassDto> collect = classDtoList.stream().sorted(Comparator.comparing(ClassDto::getCourseName)).collect(Collectors.toList());


            teachingClassDto.setClassDtos(collect);

            teachingClassDtos.add(teachingClassDto);

        });


        AtomicInteger res = new AtomicInteger();

        Map<String, List<ParameterSetting>> collect2 = parameterSettingList.stream().collect(Collectors.groupingBy(ParameterSetting::getGradeId));
        AtomicInteger count = new AtomicInteger();
        collect2.forEach((key, value) -> {
            List<Long> collect1 = value.stream().map(ParameterSetting::getCourseId).distinct().collect(Collectors.toList());
            count.addAndGet(collect1.size());
            Map<Long, List<ParameterSetting>> collect3 = value.stream().collect(Collectors.groupingBy(ParameterSetting::getCourseId));

            collect3.forEach((c, v) -> {
                int sum1 = v.stream().mapToInt(ParameterSetting::getState).sum();
                if (sum1 == v.size()) {
                    res.addAndGet(1);
                }
            });
        });


        teachingClassDtoVo.setTotalCourse((long) count.intValue());

        teachingClassDtoVo.setNoComplete((long) (count.intValue() - res.intValue()));

        teachingClassDtoVo.setTotalSize(settingIPage.getTotal());

        teachingClassDtoVo.setComplete((long) res.intValue());

        teachingClassDtoVo.setSize(records.size());

        List<TeachingClassDto> collect1 = teachingClassDtos.stream().sorted(Comparator.comparing(TeachingClassDto::getGradeName)).collect(Collectors.toList());
        teachingClassDtoVo.setTeachingClassDtos(collect1);

        return teachingClassDtoVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addParameterSetting(Integer taskId) {


        List<ParameterSetting> parameterSettingList = new ArrayList<>();


        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()

                .eq(TeachingClass::getTaskId, taskId)

                .isNull(TeachingClass::getUniqueShiftSign)

                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


//        List<Course> courseList = courseMapper.selectList(new LambdaQueryWrapper<Course>().eq(Course::getTaskId, taskId)
//
//                .eq(Course::getDeleted, Deleted.NOT.getCode()));


        List<Course> courseList = courseMapper.getCourseList(taskId);

//        List<Segment> segmentList = segmentMapper.selectList(new LambdaQueryWrapper<Segment>().eq(Segment::getTaskId, taskId)
//
//                .eq(Segment::getDeleted, Deleted.NOT.getCode()));

        List<Segment> segmentList = segmentMapper.getSegmentList(taskId);

        List<Long> teachingClassIds = teachingClassList.stream()

                .map(TeachingClass::getTeachingClassId)

                .distinct().collect(Collectors.toList());


        List<TeachingClassWeek> teachingClassWeeks = new ArrayList<>();

        if (CollUtil.isNotEmpty(teachingClassIds)) {

            teachingClassWeeks = teachingClassWeekService.lambdaQuery()

                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode())

                    .in(TeachingClassWeek::getTeachingClassId, teachingClassIds).list();

        }

        List<TeachingClassTeacher> teachingClassTeachers = new ArrayList<>();


        if (CollUtil.isNotEmpty(teachingClassIds)) {

            teachingClassTeachers = teachingClassTeacherService.lambdaQuery()

                    .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode())

                    .in(TeachingClassTeacher::getTeachingClassId, teachingClassIds).list();

        }


        Map<String, List<TeachingClass>> gradeMap = teachingClassList.stream().collect(Collectors.groupingBy(TeachingClass::getGradeId));


        //todo 对选课进行过滤筛选

        List<TeachingClassWeek> finalTeachingClassWeeks = teachingClassWeeks;

        List<TeachingClassTeacher> finalTeachingClassTeachers = teachingClassTeachers;
        gradeMap.forEach((key, value) -> {


            List<TeachingClass> collect = value.stream().filter(p -> p.getFlag().equals(1)).collect(Collectors.toList());
            List<TeachingClass> collect1 = value.stream().filter(p -> p.getFlag().equals(2)).collect(Collectors.toList());


            Map<Long, List<TeachingClass>> courseMap = collect.stream().collect(Collectors.groupingBy(TeachingClass::getCourseId));
            Map<Long, List<TeachingClass>> segmentMap = collect1.stream().collect(Collectors.groupingBy(TeachingClass::getCourseId));

            courseMap.forEach((c, cm) -> {


                Course course = courseList.stream().filter(p -> p.getCourseId().equals(c)).findFirst().orElse(null);
                TeachingClass teachingClass = cm.get(0);


                if (course != null) {


                    List<TeachingClassWeek> teachingClassWeekList = finalTeachingClassWeeks.stream()

                            .filter(p -> p.getTeachingClassId()

                                    .equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());


                    teachingClassWeekList.forEach(o -> {


                        ParameterSetting parameterSetting = new ParameterSetting();


                        parameterSetting.setTaskId(taskId);


                        parameterSetting.setTeachingClassId(teachingClass.getTeachingClassId());


                        List<TeachingClassTeacher> teachingClassTeacherList = finalTeachingClassTeachers.stream().filter(p -> p.getTeachingClassId().equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());

                        if (CollUtil.isNotEmpty(teachingClassTeacherList)) {
                            String teacherIds = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherId).map(String::valueOf).map(String::trim).collect(Collectors.joining(","));
                            String teacherNames = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherName).map(String::trim).collect(Collectors.joining(","));

                            parameterSetting.setTeacherId(teacherIds);
                            parameterSetting.setTeacherName(teacherNames);
                        }


                        parameterSetting.setTeachingClassWeekId(o.getId());


                        parameterSetting.setGradeId(teachingClass.getGradeId());

                        parameterSetting.setGradeName(teachingClass.getGradeName());


                        parameterSetting.setCourseId(teachingClass.getCourseId());

                        parameterSetting.setCourseName(teachingClass.getCourseName());


                        parameterSetting.setTeachingClassType(TeachingClassType.NOSELECT.getCode());


                        String classIds = cm.stream().map(TeachingClass::getClassId).distinct().collect(Collectors.joining(","));


                        parameterSetting.setClassIdList(classIds);


                        String teachingIds = cm.stream().map(TeachingClass::getTeachingClassId).map(String::valueOf).collect(Collectors.joining(","));


                        parameterSetting.setTeachingClassIdList(teachingIds);


                        parameterSetting.setCredit(course.getCredit());


                        parameterSetting.setAssessmentMethodId(o.getAssessmentId());


                        parameterSetting.setAssessmentMethod(o.getAssessmentName());


                        parameterSetting.setHourType(o.getHourType());


                        parameterSetting.setRoomType(o.getRoomType());


                        parameterSetting.setWeek(o.getWeek());


                        parameterSetting.setRoomId(o.getRoomId());


                        parameterSetting.setWeekNum(o.getWeekNum());


                        parameterSetting.setConnectSection(o.getConnectSection());


                        parameterSetting.setConnectNumber(o.getConnectNumber());


                        parameterSetting.setState(0);


                        parameterSetting.setStartWeek(o.getStartWeek());


                        parameterSetting.setEndWeek(o.getEndWeek());


                        parameterSetting.setSign(0);


                        parameterSetting.setFlag(1);


                        parameterSetting.setIsEnable(IsEnable.ENABLE.getCode());


                        parameterSetting.setDeleted(Deleted.NOT.getCode());


                        parameterSettingList.add(parameterSetting);


                    });


                }


            });

            segmentMap.forEach((c, cm) -> {

                Segment segment = segmentList.stream().filter(p -> p.getSegmentId().equals(c)).findFirst().orElse(null);

                TeachingClass teachingClass = cm.get(0);

                if (segment != null) {


                    List<TeachingClassWeek> teachingClassWeekList = finalTeachingClassWeeks.stream()

                            .filter(p -> p.getTeachingClassId()

                                    .equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());


                    teachingClassWeekList.forEach(o -> {


                        ParameterSetting parameterSetting = new ParameterSetting();


                        parameterSetting.setTaskId(taskId);


                        parameterSetting.setTeachingClassId(teachingClass.getTeachingClassId());


                        parameterSetting.setTeachingClassWeekId(o.getId());

                        List<TeachingClassTeacher> teachingClassTeacherList = finalTeachingClassTeachers.stream().filter(p -> p.getTeachingClassId().equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());

                        if (CollUtil.isNotEmpty(teachingClassTeacherList)) {
                            String teacherIds = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherId).map(String::valueOf).map(String::trim).collect(Collectors.joining(","));
                            String teacherNames = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherName).map(String::trim).collect(Collectors.joining(","));

                            parameterSetting.setTeacherId(teacherIds);
                            parameterSetting.setTeacherName(teacherNames);
                        }


                        parameterSetting.setGradeId(teachingClass.getGradeId());

                        parameterSetting.setGradeName(teachingClass.getGradeName());


                        parameterSetting.setCourseId(teachingClass.getCourseId());

                        parameterSetting.setCourseName(teachingClass.getCourseName());


                        String classIds = cm.stream().map(TeachingClass::getClassId).distinct().collect(Collectors.joining(","));


                        parameterSetting.setClassIdList(classIds);


                        String teachingIds = cm.stream().map(TeachingClass::getTeachingClassId).map(String::valueOf).collect(Collectors.joining(","));


                        parameterSetting.setTeachingClassIdList(teachingIds);


                        parameterSetting.setCredit(segment.getCredit());


                        parameterSetting.setWeek(o.getWeek());


                        parameterSetting.setSign(0);


                        parameterSetting.setStartWeek(o.getStartWeek());


                        parameterSetting.setEndWeek(o.getEndWeek());


                        parameterSetting.setHourType(0);


                        parameterSetting.setState(0);


                        parameterSetting.setFlag(2);


                        parameterSetting.setIsEnable(IsEnable.ENABLE.getCode());


                        parameterSetting.setDeleted(Deleted.NOT.getCode());


                        parameterSettingList.add(parameterSetting);


                    });

                }

            });

        });


        parameterSettingService.saveBatch(parameterSettingList);


        return "课程环节临时表生成完毕";


    }


    @Override
    public List<ClassInfoVoDto> getClassInfoByClassIds(Integer taskId, List<Long> classIds) {
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId)
                .in(ClassInfo::getId, classIds));
        List<ClassInfoVoDto> classInfoVoDtos = new ArrayList<>();
        classInfoList.forEach(o -> {
            ClassInfoVoDto classInfoVoDto = new ClassInfoVoDto();

            classInfoVoDto.setClassId(o.getId());
            classInfoVoDto.setClassName(o.getClassName());
            classInfoVoDto.setGradeName(o.getGradeName());
            classInfoVoDto.setMajorName(o.getMajorName());
            classInfoVoDto.setGenderName(o.getGenderName());
            classInfoVoDto.setStudentNumber(o.getStudentNumber());
            classInfoVoDtos.add(classInfoVoDto);

        });

        return classInfoVoDtos;
    }

    @Override
    public Result modifyTeachingClassInfo(Integer taskId, String gradeId, Long courseId, Integer flag, Integer
            hourType, String week, Integer totalWeekNum, Integer connectSection, Integer connectNumber, Integer
                                                  sign, Integer startWeek, Integer endWeek) {
        if (flag == 2) {
            List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>().eq(TeachingClass::getTaskId, taskId)
                    .eq(TeachingClass::getGradeId, gradeId)
                    .eq(TeachingClass::getCourseId, courseId)
                    .eq(TeachingClass::getFlag, 2).isNull(TeachingClass::getUniqueShiftSign)
                    .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


            List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());


            teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>().in(TeachingClassWeek::getTeachingClassId, teachingClassIds).
                    eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).set(TeachingClassWeek::getStartWeek, startWeek)
                    .set(TeachingClassWeek::getEndWeek, endWeek)
                    .set(TeachingClassWeek::getWeek, week)
                    .set(TeachingClassWeek::getSign, sign));


            parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>().eq(ParameterSetting::getTaskId, taskId)
                    .eq(ParameterSetting::getGradeId, gradeId)
                    .eq(ParameterSetting::getCourseId, courseId).eq(ParameterSetting::getFlag, 2)
                    .set(ParameterSetting::getWeek, week).set(ParameterSetting::getStartWeek, startWeek).set(ParameterSetting::getEndWeek, endWeek).set(ParameterSetting::getSign, sign));

            return Result.ofSuccess("环节周次已修改完毕");
        }

        Integer oneNumber = getOneNumber(week);

        if (totalWeekNum % oneNumber != 0) {

            return Result.ofFail("总学时和周次之间不是倍数关系");
        }

        Integer weekNum = totalWeekNum / oneNumber;

        if (ObjUtil.isNotNull(connectSection) && connectSection == 0 || ObjUtil.isNotNull(connectNumber) && connectNumber == 0) {
            return Result.ofFail("连上节次和连上次数不能为0");
        }

        if (weekNum < connectSection || weekNum < (connectSection * connectNumber)) {
            return Result.ofFail("周学时应该大于等于连上节次和连上次数的乘积");
        }


        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>().eq(TeachingClass::getTaskId, taskId).eq(TeachingClass::getGradeId, gradeId)
                .eq(TeachingClass::getCourseId, courseId).eq(TeachingClass::getFlag, 1)
                .isNull(TeachingClass::getUniqueShiftSign)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


        List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());


        teachingClassWeekMapper.update(null, new LambdaUpdateWrapper<TeachingClassWeek>().in(TeachingClassWeek::getTeachingClassId, teachingClassIds)
                .eq(TeachingClassWeek::getHourType, hourType).eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).set(TeachingClassWeek::getWeek, week).set(TeachingClassWeek::getSign, sign)
                .set(TeachingClassWeek::getWeekNum, weekNum).set(TeachingClassWeek::getStartWeek, startWeek).set(TeachingClassWeek::getEndWeek, endWeek).set(TeachingClassWeek::getConnectNumber, connectNumber).set(TeachingClassWeek::getConnectSection, connectSection));


        parameterSettingMapper.update(null, new LambdaUpdateWrapper<ParameterSetting>()
                .eq(ParameterSetting::getTaskId, taskId)
                .eq(ParameterSetting::getGradeId, gradeId)
                .eq(ParameterSetting::getCourseId, courseId)
                .eq(ParameterSetting::getFlag, 1)
                .eq(ParameterSetting::getHourType, hourType)
                .set(ParameterSetting::getWeek, week)
                .set(ParameterSetting::getSign, sign)
                .set(ParameterSetting::getStartWeek, startWeek)
                .set(ParameterSetting::getEndWeek, endWeek)
                .set(ParameterSetting::getConnectNumber, connectNumber).set(ParameterSetting::getWeekNum, weekNum)
                .set(ParameterSetting::getConnectSection, connectSection));


        return Result.ofSuccess("教学班信息修改完毕");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void excelToTeachingClass(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {


        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();

        List<ExcelTeachingDto> excel = this.readTeachingClassToExcel(file);


        checkExcel(excel, errorExcelVos);

        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入错误信息",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入错误信息" + time + ".xls", response);
            return;
        }

        List<ExcelTeachingClassDto> excelTeachingClasses = new ArrayList<>();

        if (CollUtil.isNotEmpty(excel)) {
            Map<String, List<ExcelTeachingDto>> collect = excel.stream().collect(Collectors.groupingBy(ExcelTeachingDto::getTeachingClassName));
            collect.forEach((key, value) -> {
                ExcelTeachingClassDto excelTeachingClassDto = new ExcelTeachingClassDto();
                if (CollUtil.isNotEmpty(value)) {
                    ExcelTeachingDto excelTeachingDto = value.get(0);
                    excelTeachingClassDto.setTeachingClassName(excelTeachingDto.getTeachingClassName());
                    excelTeachingClassDto.setCourseName(excelTeachingDto.getCourseName());
                    excelTeachingClassDto.setClassNames(StringUtils.isNotBlank(excelTeachingDto.getClassNames()) ? excelTeachingDto.getClassNames() : "");
                    excelTeachingClassDto.setStudentObject(StringUtils.isNotBlank(excelTeachingDto.getStudentObject()) ? excelTeachingDto.getStudentObject() : "");
                    excelTeachingClassDto.setGradeName(excelTeachingDto.getGradeName());
                    excelTeachingClassDto.setGradeName(excelTeachingDto.getGradeName());
                    excelTeachingClassDto.setType(excelTeachingDto.getType());
                    excelTeachingClassDto.setCampusName(excelTeachingDto.getCampusName());
                    excelTeachingClassDto.setFlag(excelTeachingDto.getFlag());
                    value.forEach(o -> {
                        if (o.getHourType().equals(1)) {
                            excelTeachingClassDto.setLectureConnectNumber(o.getLectureConnectNumber());
                            excelTeachingClassDto.setLectureConnectSection(o.getLectureConnectSection());
                            excelTeachingClassDto.setLectureRoomName(o.getLectureRoomName());
                            excelTeachingClassDto.setLectureRoomType(o.getLectureRoomType());
                            excelTeachingClassDto.setLectureWeekNum(o.getLectureWeekNum());
                            excelTeachingClassDto.setLectureWeek(StringUtils.isNotBlank(o.getLectureWeek()) ? o.getLectureWeek() : "");
                            excelTeachingClassDto.setLectureWeekNum(ObjUtil.isNotNull(o.getLectureWeekNum()) ? o.getLectureWeekNum() : 0);
                            excelTeachingClassDto.setRoomName(o.getLectureRoomName());
                            excelTeachingClassDto.setLectureTeacherNo(o.getLectureTeacherNo());
                        } else if (o.getHourType().equals(2)) {

                            excelTeachingClassDto.setExperimentalConnectNumber(o.getLectureConnectNumber());
                            excelTeachingClassDto.setExperimentalConnectSection(o.getLectureConnectSection());
                            excelTeachingClassDto.setExperimentalRoomName(o.getLectureRoomName());
                            excelTeachingClassDto.setExperimentalRoomType(o.getLectureRoomType());
                            excelTeachingClassDto.setExperimentalWeekNum(o.getLectureWeekNum());
                            excelTeachingClassDto.setExperimentalWeek(StringUtils.isNotBlank(o.getLectureWeek()) ? o.getLectureWeek() : "");
                            excelTeachingClassDto.setExperimentalWeekNum(ObjUtil.isNotNull(o.getLectureWeekNum()) ? o.getLectureWeekNum() : 0);
                            excelTeachingClassDto.setExperimentalTeacherNo(o.getLectureTeacherNo());

                        } else if (o.getHourType().equals(3)) {
                            excelTeachingClassDto.setComputerConnectNumber(o.getLectureConnectNumber());
                            excelTeachingClassDto.setComputerConnectSection(o.getLectureConnectSection());
                            excelTeachingClassDto.setComputerRoomName(o.getLectureRoomName());
                            excelTeachingClassDto.setComputerRoomType(o.getLectureRoomType());
                            excelTeachingClassDto.setComputerWeekNum(o.getLectureWeekNum());
                            excelTeachingClassDto.setComputerWeek(StringUtils.isNotBlank(o.getLectureWeek()) ? o.getLectureWeek() : "");
                            excelTeachingClassDto.setComputerWeekNum(ObjUtil.isNotNull(o.getLectureWeekNum()) ? o.getLectureWeekNum() : 0);
                            excelTeachingClassDto.setComputerTeacherNo(o.getLectureTeacherNo());

                        } else if (o.getHourType().equals(4)) {

                            excelTeachingClassDto.setOtherConnectNumber(o.getLectureConnectNumber());
                            excelTeachingClassDto.setOtherConnectSection(o.getLectureConnectSection());
                            excelTeachingClassDto.setOtherRoomName(o.getLectureRoomName());
                            excelTeachingClassDto.setOtherRoomType(o.getLectureRoomType());
                            excelTeachingClassDto.setOtherWeekNum(o.getLectureWeekNum());
                            excelTeachingClassDto.setOtherWeek(StringUtils.isNotBlank(o.getLectureWeek()) ? o.getLectureWeek() : "");
                            excelTeachingClassDto.setOtherWeekNum(ObjUtil.isNotNull(o.getLectureWeekNum()) ? o.getLectureWeekNum() : 0);
                            excelTeachingClassDto.setOtherTeacherNo(o.getLectureTeacherNo());

                        } else if (o.getHourType().equals(0)) {
                            excelTeachingClassDto.setLectureConnectNumber(null);
                            excelTeachingClassDto.setLectureConnectSection(null);
                            excelTeachingClassDto.setLectureRoomName(o.getLectureRoomName());
                            excelTeachingClassDto.setLectureRoomType(o.getLectureRoomType());
                            excelTeachingClassDto.setLectureWeekNum(o.getLectureWeekNum());
                            excelTeachingClassDto.setLectureWeek(StringUtils.isNotBlank(o.getLectureWeek()) ? o.getLectureWeek() : "");
                            excelTeachingClassDto.setLectureWeekNum(null);
                            excelTeachingClassDto.setLectureTeacherNo(o.getLectureTeacherNo());
                        }
                    });

                    excelTeachingClasses.add(excelTeachingClassDto);
                }
            });
        }


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //导入对应行政班
        List<ClassInfo> classInfoList = classInfoMapper.selectList(new LambdaQueryWrapper<ClassInfo>().eq(ClassInfo::getTaskId, taskId));


        //导入该计划对应的教学班
        List<TeachingClass> teachingClasses = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));


        List<PlanTeaching> planTeachingList = planTeachingMapper
                .selectList(new LambdaQueryWrapper<PlanTeaching>()
                        .eq(PlanTeaching::getTaskId, taskId)
                        .eq(PlanTeaching::getDeleted, Deleted.NOT.getCode()));


        List<PlanTeachingCourseSegment> planTeachingCourseSegmentList = planTeachingCourseSegmentMapper.selectList(new LambdaQueryWrapper<PlanTeachingCourseSegment>()
                .eq(PlanTeachingCourseSegment::getTaskId, taskId).eq(PlanTeachingCourseSegment::getDeleted, Deleted.NOT.getCode()));


        List<PlanTeachingStudent> planTeachingStudentList = planTeachingStudentMapper.selectList(new LambdaQueryWrapper<PlanTeachingStudent>()
                .eq(PlanTeachingStudent::getTaskId, taskId).eq(PlanTeachingStudent::getDeleted, Deleted.NOT.getCode()));

        AssessmentMethod assessmentMethod = new AssessmentMethod();
        assessmentMethod = assessmentMethodService.lambdaQuery().eq(AssessmentMethod::getTaskId, taskId).eq(AssessmentMethod::getAssessmentName, "考试").one();
        if (assessmentMethod == null) {
            assessmentMethod = new AssessmentMethod();
            assessmentMethod.setTaskId(taskId);
            assessmentMethod.setAssessmentName("考试");
            assessmentMethod.setFlag(1);
            assessmentMethod.setSchoolId(taskInfo.getSchoolId());
            assessmentMethodService.save(assessmentMethod);
        }

        //获取教学班选择的名称
        Set<String> teachingClassNames = new HashSet<>();
        if (CollUtil.isNotEmpty(teachingClasses)) {
            teachingClasses.stream().map(TeachingClass::getTeachingClassName).distinct().collect(Collectors.toSet());
        }


        //获取总周次
        int totalWeek = TimeUtils.getTotalWeek(taskInfo.getTermBeginTime(), taskInfo.getTermEndTime()).intValue();

        //获取行政班
        Map<String, ClassDtoVo> classMap = studentMapper.getClassDto(taskId, null, null)
                .stream().collect(Collectors.toMap(ClassDtoVo::getClassName, Function.identity()));


        //获取课程信息
        List<String> courseNames = excelTeachingClasses.stream().filter(p -> p.getFlag().equals(1)).map(ExcelTeachingClassDto::getCourseName).distinct().collect(Collectors.toList());
        List<String> segmentNames = excelTeachingClasses.stream().filter(p -> p.getFlag().equals(2)).map(ExcelTeachingClassDto::getCourseName).distinct().collect(Collectors.toList());


        Map<String, Course> courseMap = new HashMap<>();
        if (CollUtil.isNotEmpty(courseNames)) {
            courseMap = courseService.lambdaQuery().eq(Course::getTaskId, taskId)
                    .in(Course::getCourseName, courseNames).list()
                    .stream().collect(Collectors.toMap(Course::getCourseName, course -> course));
        }


        Map<String, Segment> segmentMap = new HashMap<>();
        if (CollUtil.isNotEmpty(segmentNames)) {
            segmentMap = segmentService.lambdaQuery().eq(Segment::getTaskId, taskId)
                    .in(Segment::getSegmentName, segmentNames).list()
                    .stream().collect(Collectors.toMap(Segment::getSegmentName, segment -> segment));
        }


        //获取学生信息
        Set<ExcelStudent> studentList = studentMapper.getStudentList(taskId);
        Map<String, List<ExcelStudent>> studentClassMap = studentList.stream().collect(Collectors.groupingBy(ExcelStudent::getClassId));

        Map<String, Long> studentIdMap = studentList.stream().collect(Collectors.toMap(ExcelStudent::getBaseStudentId, ExcelStudent::getStudentId));
        //获取教师信息
        Map<String, Teacher> teacherMap = new HashMap<>();
        List<String> teacherNos = excelTeachingClasses.stream()
                .flatMap(a -> Stream.of(a.getLectureTeacherNo(), a.getExperimentalTeacherNo(), a.getComputerTeacherNo(), a.getOtherTeacherNo()))
                .filter(StringUtils::isNotBlank)
                .distinct()
                .flatMap(item -> Arrays.stream(item.split("\\|")))
                .map(String::trim)
                .distinct()
                .collect(Collectors.toList());


        List<TaskToGrade> taskToGradeList = taskToGradeMapper.selectList(new LambdaQueryWrapper<TaskToGrade>().eq(TaskToGrade::getTaskId, taskId)
                .eq(TaskToGrade::getDeleted, Deleted.NOT.getCode()));

        Map<String, String> gradeMap = taskToGradeList.stream().collect(Collectors.toMap(TaskToGrade::getGradeName, TaskToGrade::getGradeId));


        if (CollUtil.isNotEmpty(teacherNos)) {
            teacherMap = teacherService.lambdaQuery().eq(Teacher::getSchoolId, taskInfo.getSchoolId()).eq(Teacher::getTerm, taskInfo.getTerm())
                    .in(Teacher::getBaseTeacherId, teacherNos).list()
                    .stream().collect(Collectors.toMap(Teacher::getBaseTeacherId, Function.identity(), (o1, o2) -> o1));
        }

        //获取教室信息
        Map<String, Room> roomMap = new HashMap<>();


        List<String> roomNames = new ArrayList<>();
        List<String> list1 = excelTeachingClasses.stream().filter(p -> StringUtils.isNotBlank(p.getLectureRoomName())).map(ExcelTeachingClassDto::getLectureRoomName).distinct().collect(Collectors.toList());
        List<String> list2 = excelTeachingClasses.stream().filter(p -> StringUtils.isNotBlank(p.getExperimentalRoomName())).map(ExcelTeachingClassDto::getExperimentalRoomName).distinct().collect(Collectors.toList());
        List<String> list3 = excelTeachingClasses.stream().filter(p -> StringUtils.isNotBlank(p.getComputerRoomName())).map(ExcelTeachingClassDto::getComputerRoomName).distinct().collect(Collectors.toList());
        List<String> list4 = excelTeachingClasses.stream().filter(p -> StringUtils.isNotBlank(p.getOtherRoomName())).map(ExcelTeachingClassDto::getOtherRoomName).distinct().collect(Collectors.toList());
        roomNames.addAll(list1);
        roomNames.addAll(list2);
        roomNames.addAll(list3);
        roomNames.addAll(list4);
//        List<ExcelTeachingClassDto> excelTeachingClassDtos = excelTeachingClasses.stream()
//                .filter(a -> StringUtils.isNotBlank(a.getLectureRoomName()) || StringUtils.isNotBlank(a.getExperimentalRoomName()) || StringUtils.isNotBlank(a.getComputerRoomName()) || StringUtils.isNotBlank(a.getOtherRoomName())).collect(Collectors.toList());
//
//
//            List<String> roomNames = excelTeachingClassDtos.stream()
//                    .flatMap(a -> Stream.of(a.getLectureRoomName(), a.getExperimentalRoomName(), a.getComputerRoomName(), a.getOtherRoomName()))
//                    .distinct().map(String::trim).collect(Collectors.toList());

        roomNames = roomNames.stream().map(String::trim).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(roomNames)) {
            roomMap = roomService.lambdaQuery().eq(Room::getSchoolId, taskInfo.getSchoolId()).eq(Room::getTerm, taskInfo.getTerm()).in(Room::getRoomName, roomNames).list()
                    .stream().distinct().collect(Collectors.toMap(Room::getRoomName, Function.identity(), (o1, o2) -> o1));
        }


        //获取校区
        Map<String, String> campusMap = roomMapper.getCampusList(taskInfo.getSchoolId(), taskInfo.getTerm())
                .stream().collect(Collectors.toMap(Campus::getCampusName, Campus::getCampusId));


        //待插入数据 教学班 教学班对应学生 教学班对应教师 教学班参数设置
        List<TeachingClass> teachingClassList = new ArrayList<>();
        List<TeachingClassStudent> teachingClassStudentList = new ArrayList<>();
        List<TeachingClassTeacher> teachingClassTeacherList = new ArrayList<>();
        List<TeachingClassWeek> teachingClassWeekList = new ArrayList<>();


        //记录当前行数
        long index = 3;
        for (ExcelTeachingClassDto excelTeachingClass : excelTeachingClasses) {
            //存储当前行唯一标识
            excelTeachingClass.setTeachingClassId(index);
            index++;
        }


        //错误日志
        List<Map<String, Object>> errorMapList = new ArrayList<>(excelTeachingClasses.size());
        StringJoiner stringJoiner;
        for (ExcelTeachingClassDto excelTeachingClassDto : excelTeachingClasses) {

            List<String> baseStudentIds = new ArrayList<>();

            stringJoiner = new StringJoiner("\n");
            Map<String, String> studentObjectMap = formatStudentObject(excelTeachingClassDto.getStudentObject());

            if (excelTeachingClassDto.getFlag().equals(1)) {
                if (!courseMap.containsKey(excelTeachingClassDto.getCourseName().trim())) {
                    stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行课程名称不存在:" + excelTeachingClassDto.getCourseName());
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                    errorExcelVo.setErrorMsg("课程名称不存在" + excelTeachingClassDto.getCourseName());
                    errorExcelVos.add(errorExcelVo);
                } else {

                    Map<String, Course> finalCourseMap = courseMap;
                    List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentList.stream()
                            .filter(p -> p.getBaseCourseId().equals(finalCourseMap.get(excelTeachingClassDto.getCourseName())
                                    .getBaseCourseId()))
                            .collect(Collectors.toList());

                    if (CollUtil.isEmpty(planTeachingCourseSegments)) {
                        stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行课程本学期未有教学计划:" + excelTeachingClassDto.getCourseName());
                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                        errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                        errorExcelVo.setErrorMsg("课程本学期没有教学计划" + excelTeachingClassDto.getCourseName());
                        errorExcelVos.add(errorExcelVo);
                    } else {

                        List<String> basePlanTeachingIds = planTeachingCourseSegments.stream().map(PlanTeachingCourseSegment::getBaseTeachingPlanId).distinct()
                                .collect(Collectors.toList());


                        List<PlanTeaching> planTeachings = planTeachingList.stream()
                                .filter(p -> basePlanTeachingIds.contains(p.getBaseTeachingPlanId()))
                                .filter(p -> p.getGradeId().equals(gradeMap.get(excelTeachingClassDto.getGradeName())))
                                .distinct().collect(Collectors.toList());

                        if (CollUtil.isEmpty(planTeachings)) {
                            stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行课程本学期本年级本专业未有该课程的教学计划:" + excelTeachingClassDto.getCourseName());
                            ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                            errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                            errorExcelVo.setErrorMsg("课程本学期本年级本专业未有该课程的教学计划" + excelTeachingClassDto.getCourseName());
                            errorExcelVos.add(errorExcelVo);
                        } else {
                            List<PlanTeachingStudent> planTeachingStudents = planTeachingStudentList.stream()
                                    .filter(p -> planTeachings.stream().anyMatch(o -> o.getBaseTeachingPlanId().equals(p.getBaseTeachingPlanId())))
                                    .distinct().collect(Collectors.toList());


                            baseStudentIds = planTeachingStudents.stream().map(PlanTeachingStudent::getBaseStudentId)
                                    .distinct().collect(Collectors.toList());


                            List<String> classIds = studentList.stream()
                                    .filter(p -> planTeachingStudents.stream().anyMatch(o -> o.getBaseStudentId().equals(p.getBaseStudentId())))
                                    .distinct().map(ExcelStudent::getClassId).distinct().collect(Collectors.toList());

                            List<String> classNameList = classInfoList.stream().filter(p -> classIds.stream().anyMatch(o -> o.equals(p.getClassId())))
                                    .distinct().map(ClassInfo::getClassName).map(String::trim).distinct().collect(Collectors.toList());


                            if (StringUtils.isNotBlank(excelTeachingClassDto.getClassNames())) {
                                if (!classNameList.contains(excelTeachingClassDto.getClassNames().trim())) {
                                    stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行该教学班对应行政班在本学期本年级本专业没有该课程的教学计划" + excelTeachingClassDto.getCourseName());
                                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                                    errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                                    errorExcelVo.setErrorMsg("该教学班对应行政班在本学期本年级本专业没有该课程的教学计划" + excelTeachingClassDto.getClassNames());
                                    errorExcelVos.add(errorExcelVo);
                                }

                            }

                            //待插入教学班对应学生 该行政班学生及改学号学生
                            String studentIds = studentObjectMap.get("studentIds");
                            if (StrUtil.isNotBlank(studentIds)) {
                                for (String studentId : studentIds.split("[,，]")) {
                                    studentId = studentId.trim();
                                    if (!baseStudentIds.contains(studentId)) {
                                        stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行学生不在该教学班的上课范围不存在:" + studentId);
                                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                                        errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                                        errorExcelVo.setErrorMsg("学生不在该教学班的上课范围不存在" + studentId);
                                        errorExcelVos.add(errorExcelVo);
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (excelTeachingClassDto.getFlag().equals(2)) {
                if (!segmentMap.containsKey(excelTeachingClassDto.getCourseName().trim())) {
                    stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行环节名称不存在:" + excelTeachingClassDto.getCourseName());
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                    errorExcelVo.setErrorMsg("环节名称不存在" + excelTeachingClassDto.getCourseName());
                    errorExcelVos.add(errorExcelVo);
                } else {

                    Map<String, Segment> finalSegmentMap = segmentMap;
                    List<PlanTeachingCourseSegment> planTeachingCourseSegments = planTeachingCourseSegmentList.stream()
                            .filter(p -> p.getBaseCourseId().equals(finalSegmentMap.get(excelTeachingClassDto.getCourseName())
                                    .getBaseSegmentId()))
                            .collect(Collectors.toList());

                    if (CollUtil.isEmpty(planTeachingCourseSegments)) {
                        stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行环节本学期未有教学计划:" + excelTeachingClassDto.getCourseName());
                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                        errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                        errorExcelVo.setErrorMsg("环节本学期没有教学计划" + excelTeachingClassDto.getCourseName());
                        errorExcelVos.add(errorExcelVo);
                    } else {

                        List<String> basePlanTeachingIds = planTeachingCourseSegments.stream().map(PlanTeachingCourseSegment::getBaseTeachingPlanId).distinct()
                                .collect(Collectors.toList());


                        List<PlanTeaching> planTeachings = planTeachingList.stream()
                                .filter(p -> basePlanTeachingIds.contains(p.getBaseTeachingPlanId()))
                                .filter(p -> p.getGradeId().equals(gradeMap.get(excelTeachingClassDto.getGradeName())))
                                .distinct().collect(Collectors.toList());

                        if (CollUtil.isEmpty(planTeachings)) {
                            stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行环节本学期本年级本专业未有该课程的教学计划:" + excelTeachingClassDto.getCourseName());
                            ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                            errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                            errorExcelVo.setErrorMsg("环节本学期本年级本专业未有该课程的教学计划" + excelTeachingClassDto.getCourseName());
                            errorExcelVos.add(errorExcelVo);
                        } else {
                            List<PlanTeachingStudent> planTeachingStudents = planTeachingStudentList.stream()
                                    .filter(p -> planTeachings.stream().anyMatch(o -> o.getBaseTeachingPlanId().equals(p.getBaseTeachingPlanId())))
                                    .distinct().collect(Collectors.toList());


                            baseStudentIds = planTeachingStudents.stream().map(PlanTeachingStudent::getBaseStudentId)
                                    .distinct().collect(Collectors.toList());


                            List<String> classIds = studentList.stream()
                                    .filter(p -> planTeachingStudents.stream().anyMatch(o -> o.getBaseStudentId().equals(p.getBaseStudentId())))
                                    .distinct().map(ExcelStudent::getClassId).distinct().collect(Collectors.toList());

                            List<String> classNameList = classInfoList.stream().filter(p -> classIds.stream().anyMatch(o -> o.equals(p.getClassId())))
                                    .distinct().map(ClassInfo::getClassName).map(String::trim).distinct().collect(Collectors.toList());


                            if (StringUtils.isNotBlank(excelTeachingClassDto.getClassNames())) {
                                if (!classNameList.contains(excelTeachingClassDto.getClassNames())) {
                                    stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行该教学班对应行政班在本学期本年级本专业没有该课程的教学计划" + excelTeachingClassDto.getCourseName());
                                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                                    errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                                    errorExcelVo.setErrorMsg("该教学班对应行政班在本学期本年级本专业没有该课程的教学计划" + excelTeachingClassDto.getClassNames());
                                    errorExcelVos.add(errorExcelVo);
                                }
                            }
                            //待插入教学班对应学生 该行政班学生及改学号学生
                            String studentIds = studentObjectMap.get("studentIds");
                            if (StrUtil.isNotBlank(studentIds)) {
                                for (String studentId : studentIds.split("[,，]")) {
                                    studentId = studentId.trim();
                                    if (!baseStudentIds.contains(studentId)) {
                                        stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行学生不在该教学班的上课范围不存在:" + studentId);
                                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                                        errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                                        errorExcelVo.setErrorMsg("学生不在该教学班的上课范围不存在" + studentId);
                                        errorExcelVos.add(errorExcelVo);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (!campusMap.containsKey(excelTeachingClassDto.getCampusName().trim())) {
                stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行校区名称不存在:" + excelTeachingClassDto.getCampusName());
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                errorExcelVo.setErrorMsg("校区名称不存在" + excelTeachingClassDto.getCampusName());
                errorExcelVos.add(errorExcelVo);
            }

            //判断教学班级名称是否正确
            if (StrUtil.isBlank(excelTeachingClassDto.getClassNames()) && excelTeachingClassDto.getFlag().equals(1) && excelTeachingClassDto.getType().equals(0)) {
                stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行教学班对应行政班名称不能为空");
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                errorExcelVo.setErrorMsg("教学班对应行政班名称不能为空");
                errorExcelVos.add(errorExcelVo);
            } else {
                if (!teachingClassNames.contains(excelTeachingClassDto.getTeachingClassName())) {
                    teachingClassNames.add(excelTeachingClassDto.getTeachingClassName());
                } else {
                    stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行教学班名称重复");
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                    errorExcelVo.setErrorMsg("教学班名称重复");
                    errorExcelVos.add(errorExcelVo);
                }

                if (excelTeachingClassDto.getType().equals(0)) {
                    for (String className : excelTeachingClassDto.getClassNames().split("[,，]")) {
                        className = className.trim();
                        if (!classMap.containsKey(className)) {
                            stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行教学班对于行政班班级名称不存在:" + className);

                            ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                            errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                            errorExcelVo.setErrorMsg("教学班对应行政班班级不存在" + className);
                            errorExcelVos.add(errorExcelVo);
                        }
                    }
                }
            }

            //拆班教学班roomId是否存在
            if (StrUtil.isNotBlank(excelTeachingClassDto.getLectureRoomName()) && !roomMap.containsKey(excelTeachingClassDto.getLectureRoomName().trim())) {
                stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行讲授上课场地不存在:" + excelTeachingClassDto.getLectureRoomName());
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                errorExcelVo.setErrorMsg("讲授上课场地不存在" + excelTeachingClassDto.getLectureRoomName());
                errorExcelVos.add(errorExcelVo);
            }
            if (StrUtil.isNotBlank(excelTeachingClassDto.getExperimentalRoomName()) && !roomMap.containsKey(excelTeachingClassDto.getExperimentalRoomName().trim())) {
                stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行实验上课场地不存在:" + excelTeachingClassDto.getExperimentalRoomName());
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                errorExcelVo.setErrorMsg("实验上课场地不存在" + excelTeachingClassDto.getExperimentalRoomName());
                errorExcelVos.add(errorExcelVo);
            }
            if (StrUtil.isNotBlank(excelTeachingClassDto.getComputerRoomName()) && !roomMap.containsKey(excelTeachingClassDto.getComputerRoomName())) {
                stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行上机上课场地不存在:" + excelTeachingClassDto.getComputerRoomName());
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                errorExcelVo.setErrorMsg("上机场地不存在" + excelTeachingClassDto.getComputerRoomName());
                errorExcelVos.add(errorExcelVo);
            }
            if (StrUtil.isNotBlank(excelTeachingClassDto.getOtherRoomName()) && !roomMap.containsKey(excelTeachingClassDto.getOtherRoomName().trim())) {
                stringJoiner.add("第" + excelTeachingClassDto.getTeachingClassId() + "行其他上课场地不存在:" + excelTeachingClassDto.getOtherRoomName());

                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingClassDto.getTeachingClassId());
                errorExcelVo.setErrorMsg("其他上课场地不存在" + excelTeachingClassDto.getComputerRoomName());
                errorExcelVos.add(errorExcelVo);
            }
            if (stringJoiner.toString().length() == 0) {
                //行政班名转化为行政班id
                String classIds = "";

                List<String> studentIds = new ArrayList<>();
                if (excelTeachingClassDto.getType().equals(0)) {

                    if (StrUtil.isNotBlank(studentObjectMap.get("classIds"))) {
                        for (String className : studentObjectMap.get("classIds").split("[,，]")) {
                            className = className.trim();
                            for (ExcelStudent excelStudent : studentClassMap.get(classMap.get(className).getClassId())) {
                                String baseStudentId = excelStudent.getBaseStudentId().trim();
                                if (baseStudentIds.contains(baseStudentId)) {
                                    studentIds.add(baseStudentId);
                                }
                            }
                            classIds += classMap.get(className).getClassName() + ",";
                        }

                    }
                    if (StrUtil.isNotBlank(classIds)) {
                        classIds = classIds.substring(0, classIds.length() - 1);
                    }

                }


                //待插入教学班对应学生 该行政班学生及改学号学生
                if (StrUtil.isNotBlank(studentObjectMap.get("studentIds"))) {
                    for (String studentId : studentObjectMap.get("studentIds").split("[,，]")) {
                        studentId = studentId.trim();
                        if (baseStudentIds.contains(studentId)) {
                            studentIds.add(studentId);
                        }
                    }
                }

                List<ClassInfo> classInfos = classInfoList.stream().filter(p -> p.getClassName().equals(excelTeachingClassDto.getClassNames().trim())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(classInfos) || excelTeachingClassDto.getType().equals(1)) {
                    //寻常教学班
                    if (excelTeachingClassDto.getType().equals(0)) {
                        ClassInfo classInfo = classInfos.get(0);
                        if (excelTeachingClassDto.getFlag().equals(1)) {
                            teachingClassList.add(new TeachingClass().setTaskId(taskId)
                                    .setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeachingClassName(excelTeachingClassDto.getTeachingClassName())
                                    .setCourseId(courseMap.get(excelTeachingClassDto.getCourseName()).getCourseId())
                                    .setCourseName(excelTeachingClassDto.getCourseName())
                                    .setClassId(String.valueOf(classInfo.getId()))
                                    .setGradeName(excelTeachingClassDto.getGradeName())
                                    .setGradeId(gradeMap.get(excelTeachingClassDto.getGradeName()))
                                    .setClassName(excelTeachingClassDto.getClassNames())
                                    .setTeachingClassType(excelTeachingClassDto.getType())
                                    .setFlag(excelTeachingClassDto.getFlag())
                                    .setState(1)
                                    .setCampusId(campusMap.get(excelTeachingClassDto.getCampusName()))
                                    .setCampusName(excelTeachingClassDto.getCampusName())
                                    .setClassNum(studentIds.size()));
                        } else if (excelTeachingClassDto.getFlag().equals(2)) {
                            teachingClassList.add(new TeachingClass().setTaskId(taskId)
                                    .setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeachingClassName(excelTeachingClassDto.getTeachingClassName())
                                    .setCourseId(segmentMap.get(excelTeachingClassDto.getCourseName()).getSegmentId())
                                    .setCourseName(excelTeachingClassDto.getCourseName())
                                    .setClassId(String.valueOf(classInfo.getId()))
                                    .setGradeName(excelTeachingClassDto.getGradeName())
                                    .setGradeId(gradeMap.get(excelTeachingClassDto.getGradeName()))
                                    .setClassName(excelTeachingClassDto.getClassNames())
                                    .setTeachingClassType(excelTeachingClassDto.getType())
                                    .setFlag(excelTeachingClassDto.getFlag())
                                    .setState(1)
                                    .setCampusId(campusMap.get(excelTeachingClassDto.getCampusName()))
                                    .setCampusName(excelTeachingClassDto.getCampusName())
                                    .setClassNum(studentIds.size()));
                        }
                    } else if (excelTeachingClassDto.getType().equals(1)) {
                        teachingClassList.add(new TeachingClass().setTaskId(taskId)
                                .setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                .setTeachingClassName(excelTeachingClassDto.getTeachingClassName())
                                .setCourseId(courseMap.get(excelTeachingClassDto.getCourseName()).getCourseId())
                                .setCourseName(excelTeachingClassDto.getCourseName())
                                .setClassId(null)
                                .setClassName(null)
                                .setState(1)
                                .setGradeName(excelTeachingClassDto.getGradeName())
                                .setGradeId(gradeMap.get(excelTeachingClassDto.getGradeName()))
                                .setTeachingClassType(excelTeachingClassDto.getType())
                                .setFlag(excelTeachingClassDto.getFlag())
                                .setCampusId(campusMap.get(excelTeachingClassDto.getCampusName()))
                                .setCampusName(excelTeachingClassDto.getCampusName())
                                .setClassNum(baseStudentIds.size()));
                    }
                }


                //待插入教学班对应学生 该行政班学生及改学号学生
                if (excelTeachingClassDto.getType().equals(0)) {
                    if (CollUtil.isNotEmpty(studentIds)) {
                        for (String studentId : studentIds) {
                            studentId = studentId.trim();
                            teachingClassStudentList.add(new TeachingClassStudent().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setStudentId(studentIdMap.get(studentId))
                                    .setFlag(1));
                        }
                    }
                }


                if (excelTeachingClassDto.getFlag().equals(1)) {
                    //待插入教学班对应教师
                    if (StrUtil.isNotBlank(excelTeachingClassDto.getLectureTeacherNo())) {
                        for (String teacherNo : excelTeachingClassDto.getLectureTeacherNo().split("\\|")) {
                            teacherNo = teacherNo.trim(); // 去除空格
                            teachingClassTeacherList.add(new TeachingClassTeacher()
                                    .setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeacherId(teacherMap.get(teacherNo).getTeacherId())
                                    .setTeacherName(teacherMap.get(teacherNo).getTeacherName())
                                    .setTeacherType(1));
                        }
                    }

                    if (StrUtil.isNotBlank(excelTeachingClassDto.getExperimentalTeacherNo())) {
                        for (String teacherNo : excelTeachingClassDto.getExperimentalTeacherNo().split("\\|")) {
                            teacherNo = teacherNo.trim(); // 去除空格
                            teachingClassTeacherList.add(new TeachingClassTeacher().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeacherId(teacherMap.get(teacherNo).getTeacherId())
                                    .setTeacherName(teacherMap.get(teacherNo).getTeacherName())
                                    .setTeacherType(2));
                        }
                    }

                    if (StrUtil.isNotBlank(excelTeachingClassDto.getComputerTeacherNo())) {
                        for (String teacherNo : excelTeachingClassDto.getComputerTeacherNo().split("\\|")) {
                            teacherNo = teacherNo.trim(); // 去除空格
                            teachingClassTeacherList.add(new TeachingClassTeacher().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeacherId(teacherMap.get(teacherNo).getTeacherId())
                                    .setTeacherName(teacherMap.get(teacherNo).getTeacherName())
                                    .setTeacherType(3));
                        }
                    }


                    if (StrUtil.isNotBlank(excelTeachingClassDto.getOtherTeacherNo())) {
                        for (String teacherNo : excelTeachingClassDto.getOtherTeacherNo().split("\\|")) {
                            teacherNo = teacherNo.trim(); // 去除空格
                            teachingClassTeacherList.add(new TeachingClassTeacher().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeacherId(teacherMap.get(teacherNo).getTeacherId())
                                    .setTeacherName(teacherMap.get(teacherNo).getTeacherName())
                                    .setTeacherType(4));
                        }
                    }
                } else if (excelTeachingClassDto.getFlag().equals(2)) {
                    if (StrUtil.isNotBlank(excelTeachingClassDto.getLectureTeacherNo())) {
                        for (String teacherNo : excelTeachingClassDto.getLectureTeacherNo().split("\\|")) {
                            teacherNo = teacherNo.trim(); // 去除空格
                            teachingClassTeacherList.add(new TeachingClassTeacher()
                                    .setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                    .setTeacherId(teacherMap.get(teacherNo).getTeacherId())
                                    .setTeacherName(teacherMap.get(teacherNo).getTeacherName())
                                    .setTeacherType(0));
                        }
                    }
                }


                if (excelTeachingClassDto.getFlag().equals(1)) {
                    //待插入教学班参数设置
                    if (StrUtil.isNotBlank(excelTeachingClassDto.getLectureWeek())) {
                        teachingClassWeekList.add(new TeachingClassWeek().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                .setWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getLectureWeek(), totalWeek))
                                .setWeekNum(excelTeachingClassDto.getLectureWeekNum())
                                .setStartWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getLectureWeek(), totalWeek).indexOf('1') + 1)
                                .setEndWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getLectureWeek(), totalWeek).lastIndexOf('1') + 1)
                                .setConnectSection(excelTeachingClassDto.getLectureConnectSection() == null ? 1 : excelTeachingClassDto.getLectureConnectSection())
                                .setConnectNumber(excelTeachingClassDto.getLectureConnectNumber() == null ? 0 : excelTeachingClassDto.getLectureConnectNumber())
                                .setRoomType(StrUtil.isNotBlank(excelTeachingClassDto.getLectureRoomName()) ? roomMap.get(excelTeachingClassDto.getLectureRoomName().trim()).getRoomType() : excelTeachingClassDto.getLectureRoomType())
                                .setAssessmentId(assessmentMethod.getAssessmentId())
                                .setAssessmentName(assessmentMethod.getAssessmentName())
                                .setRoomId(StrUtil.isNotBlank(excelTeachingClassDto.getLectureRoomName()) ? roomMap.get(excelTeachingClassDto.getLectureRoomName().trim()).getRoomId() : null)
                                .setHourType(1));
                    }
                    if (StrUtil.isNotBlank(excelTeachingClassDto.getExperimentalWeek())) {
                        teachingClassWeekList.add(new TeachingClassWeek().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                .setWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getExperimentalWeek(), totalWeek))
                                .setWeekNum(excelTeachingClassDto.getExperimentalWeekNum())
                                .setStartWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getExperimentalWeek(), totalWeek).indexOf('1') + 1)
                                .setEndWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getExperimentalWeek(), totalWeek).lastIndexOf('1') + 1)
                                .setConnectSection(excelTeachingClassDto.getExperimentalConnectSection() == null ? 1 : excelTeachingClassDto.getExperimentalConnectSection())
                                .setConnectNumber(excelTeachingClassDto.getExperimentalConnectNumber() == null ? 0 : excelTeachingClassDto.getExperimentalConnectNumber())
                                .setRoomType(StrUtil.isNotBlank(excelTeachingClassDto.getExperimentalRoomName()) ? roomMap.get(excelTeachingClassDto.getExperimentalRoomName().trim()).getRoomType() : excelTeachingClassDto.getExperimentalRoomType())
                                .setAssessmentId(assessmentMethod.getAssessmentId())
                                .setAssessmentName(assessmentMethod.getAssessmentName())
                                .setRoomId(StrUtil.isNotBlank(excelTeachingClassDto.getExperimentalRoomName()) ? roomMap.get(excelTeachingClassDto.getExperimentalRoomName().trim()).getRoomId() : null)
                                .setHourType(2));
                    }
                    if (StrUtil.isNotBlank(excelTeachingClassDto.getComputerWeek())) {
                        teachingClassWeekList.add(new TeachingClassWeek().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                .setWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getComputerWeek(), totalWeek))
                                .setWeekNum(excelTeachingClassDto.getComputerWeekNum())
                                .setStartWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getComputerWeek(), totalWeek).indexOf('1') + 1)
                                .setEndWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getComputerWeek(), totalWeek).lastIndexOf('1') + 1)
                                .setConnectSection(excelTeachingClassDto.getComputerConnectSection() == null ? 1 : excelTeachingClassDto.getComputerConnectSection())
                                .setConnectNumber(excelTeachingClassDto.getComputerConnectNumber() == null ? 0 : excelTeachingClassDto.getComputerConnectNumber())
                                .setAssessmentId(assessmentMethod.getAssessmentId())
                                .setAssessmentName(assessmentMethod.getAssessmentName())
                                .setRoomType(StrUtil.isNotBlank(excelTeachingClassDto.getComputerRoomName()) ? roomMap.get(excelTeachingClassDto.getComputerRoomName().trim()).getRoomType() : excelTeachingClassDto.getComputerRoomType())
                                .setRoomId(StrUtil.isNotBlank(excelTeachingClassDto.getComputerRoomName()) ? roomMap.get(excelTeachingClassDto.getComputerRoomName().trim()).getRoomId() : null)
                                .setHourType(3));
                    }
                    if (StrUtil.isNotBlank(excelTeachingClassDto.getOtherWeek())) {
                        teachingClassWeekList.add(new TeachingClassWeek().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                                .setWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getOtherWeek(), totalWeek))
                                .setWeekNum(excelTeachingClassDto.getOtherWeekNum())
                                .setStartWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getOtherWeek(), totalWeek).indexOf('1') + 1)
                                .setEndWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getOtherWeek(), totalWeek).lastIndexOf('1') + 1)
                                .setConnectSection(excelTeachingClassDto.getOtherConnectSection() == null ? 1 : excelTeachingClassDto.getOtherConnectSection())
                                .setConnectNumber(excelTeachingClassDto.getOtherConnectNumber() == null ? 0 : excelTeachingClassDto.getOtherConnectNumber())
                                .setAssessmentId(assessmentMethod.getAssessmentId())
                                .setAssessmentName(assessmentMethod.getAssessmentName())
                                .setRoomType(StrUtil.isNotBlank(excelTeachingClassDto.getOtherRoomName()) ? roomMap.get(excelTeachingClassDto.getOtherRoomName().trim()).getRoomType() : excelTeachingClassDto.getOtherRoomType())
                                .setRoomId(StrUtil.isNotBlank(excelTeachingClassDto.getOtherRoomName()) ? roomMap.get(excelTeachingClassDto.getOtherRoomName().trim()).getRoomId() : null)
                                .setHourType(4));
                    }
                } else if (excelTeachingClassDto.getFlag().equals(2)) {
                    teachingClassWeekList.add(new TeachingClassWeek().setTeachingClassId(excelTeachingClassDto.getTeachingClassId())
                            .setWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getLectureWeek(), totalWeek))
                            .setWeekNum(excelTeachingClassDto.getLectureWeekNum())
                            .setStartWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getLectureWeek(), totalWeek).indexOf('1') + 1)
                            .setEndWeek(ExcelFormatUtil.toBinary(excelTeachingClassDto.getLectureWeek(), totalWeek).lastIndexOf('1') + 1)
                            .setConnectSection(excelTeachingClassDto.getLectureConnectSection() == null ? 1 : excelTeachingClassDto.getLectureConnectSection())
                            .setConnectNumber(excelTeachingClassDto.getLectureConnectNumber() == null ? 0 : excelTeachingClassDto.getLectureConnectNumber())
                            .setRoomType(StrUtil.isNotBlank(excelTeachingClassDto.getLectureRoomName()) ? roomMap.get(excelTeachingClassDto.getLectureRoomName().trim()).getRoomType() : excelTeachingClassDto.getLectureRoomType())
                            .setAssessmentId(assessmentMethod.getAssessmentId())
                            .setAssessmentName(assessmentMethod.getAssessmentName())
                            .setRoomId(StrUtil.isNotBlank(excelTeachingClassDto.getLectureRoomName()) ? roomMap.get(excelTeachingClassDto.getLectureRoomName().trim()).getRoomId() : null)
                            .setHourType(0));
                }
            } else {
                Map<String, Object> errorMap = new LinkedHashMap<>(2);
                errorMap.put("原Excel行号", index);
                errorMap.put("错误原因", stringJoiner.toString());
                errorMapList.add(errorMap);
            }
        }
        Integer size1 = errorExcelVos.size();


        if (CollUtil.isNotEmpty(errorExcelVos)) {

            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));


            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入错误信息",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入错误信息" + time + ".xls", response);
        }

        //插入教学班
        if (size1.equals(0)) {
            if (flag == 2) {
                List<Long> collect = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).list().stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());
                //覆盖之前的教学班
                if (CollUtil.isNotEmpty(collect)) {
                    teachingClassService.lambdaUpdate().eq(TeachingClass::getTaskId, taskId).remove();
                    teachingClassWeekService.lambdaUpdate().in(TeachingClassWeek::getTeachingClassId, collect).remove();
                    teachingClassTeacherService.lambdaUpdate().in(TeachingClassTeacher::getTeachingClassId, collect).remove();
                    teachingClassStudentService.lambdaUpdate().in(TeachingClassStudent::getTeachingClassId, collect).remove();
                }

                Map<Long, List<TeachingClass>> collect1 = teachingClassList.stream().filter(p -> p.getTeachingClassType().equals(1)).collect(Collectors.groupingBy(TeachingClass::getCourseId));
                collect1.forEach((key, value) -> {
                    TeachingClass teachingClass = value.get(0);
                    Integer classNum = teachingClass.getClassNum();
                    int size = value.size();

                    int count = classNum / (ObjUtil.isNotNull(size) ? size : 1);

                    value.forEach(o -> {
                        o.setClassNum(count);
                    });

                    if (count % classNum != 0) {
                        int a = count % classNum;
                        for (int i = 0; i < a; i++) {
                            value.get(i).setClassNum(value.get(i).getClassNum() + 1);
                        }
                    }
                });

                teachingClassService.saveBatch(teachingClassList);
                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);
                teachingClassTeacherService.saveOrUpdateBatch(teachingClassTeacherList);
                teachingClassStudentService.saveOrUpdateBatch(teachingClassStudentList);
            } else {
                List<TeachingClass> list = teachingClassService.lambdaQuery().orderByDesc(TeachingClass::getTeachingClassId).list();
                List<TeachingClass> collect = list.stream().filter(p -> p.getTeachingClassType().equals(1) && p.getDeleted().equals(Deleted.NOT.getCode())).collect(Collectors.toList());
                Map<Long, List<TeachingClass>> collect1 = collect.stream().collect(Collectors.groupingBy(TeachingClass::getCourseId));

                List<Integer> sum = new ArrayList<>();
                if (CollUtil.isNotEmpty(collect)) {
                    List<TeachingClass> updateTeachingClass = new ArrayList<>();
                    collect1.forEach((key, value) -> {
                        List<TeachingClass> collect2 = teachingClassList.stream().filter(p -> p.getFlag().equals(1) && p.getTeachingClassType().equals(1) && p.getCourseId().equals(key)).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(collect2)) {
                            sum.add(1);
                            Integer classNum = collect2.get(0).getClassNum();

                            int size = value.size() + collect2.size();

                            int count = classNum / (ObjUtil.isNotNull(size) ? size : 1);

                            value.forEach(o -> {
                                o.setClassNum(count);
                            });
                            collect2.forEach(o -> {
                                o.setClassNum(count);
                            });

                            if (classNum % size != 0) {
                                int a = classNum % size;
                                for (int i = 0; i < a; i++) {
                                    value.get(i % value.size()).setClassNum(value.get(i % value.size()).getClassNum() + 1);
                                }
                            }

                            updateTeachingClass.addAll(value);
                        }
                    });
                    if (CollUtil.isNotEmpty(updateTeachingClass)) {
                        teachingClassService.saveOrUpdateBatch(updateTeachingClass);
                    }
                }


                if (CollUtil.isEmpty(sum)) {
                    List<TeachingClass> collect2 = teachingClassList.stream()
                            .filter(p -> p.getFlag().equals(1) && p.getTeachingClassType()
                                    .equals(1)).collect(Collectors.toList());
                    Map<String, List<TeachingClass>> collect3 = collect2.stream().collect(Collectors.groupingBy(TeachingClass::getCourseName));

                    collect3.forEach((key, value) -> {
                        Integer classNum = value.get(0).getClassNum();
                        int size = value.size();
                        int count = classNum / (ObjUtil.isNotNull(size) ? size : 1);
                        value.forEach(o -> {
                            o.setClassNum(count);
                        });

                        if (classNum % size != 0) {
                            int a = classNum % size;
                            for (int i = 0; i < a; i++) {
                                value.get(i % value.size()).setClassNum(value.get(i % value.size()).getClassNum() + 1);
                            }
                        }
                    });

                }


                Long teachingClassId = 0L;

                if (CollUtil.isNotEmpty(list)) {
                    TeachingClass teachingClass = list.get(0);
                    teachingClassId = teachingClass.getTeachingClassId();
                }


                Long finalTeachingClassId = teachingClassId;
                teachingClassList.forEach(o -> {
                    o.setTeachingClassId(o.getTeachingClassId() + finalTeachingClassId);
                });

                teachingClassWeekList.forEach(o -> {
                    o.setTeachingClassId(o.getTeachingClassId() + finalTeachingClassId);
                });

                teachingClassTeacherList.forEach(o -> {
                    o.setTeachingClassId(o.getTeachingClassId() + finalTeachingClassId);
                });

                teachingClassStudentList.forEach(o -> {
                    o.setTeachingClassId(o.getTeachingClassId() + finalTeachingClassId);
                });
                teachingClassService.saveBatch(teachingClassList);
                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeekList);
                teachingClassTeacherService.saveOrUpdateBatch(teachingClassTeacherList);
                teachingClassStudentService.saveOrUpdateBatch(teachingClassStudentList);
            }

            redisUtil.del("cvas:com.lancoo.cvas.mapper.TeachingClassMapper");
        }

        parameterSettingService.lambdaUpdate().eq(ParameterSetting::getTaskId, taskId).remove();
        teachingClassService.addParameterSetting(taskId);
    }

    private Map<String, String> formatStudentObject(String studentObject) {
        Map<String, String> result = new HashMap<>();
        result.put("studentIds", "");
        result.put("classIds", "");
        String[] parts = studentObject.split(";");
        for (String part : parts) {
            String[] subParts = part.split("\\|");
            if (subParts.length == 2) {
                String type = subParts[0];
                String values = subParts[1];
                if ("C".equals(type)) {
                    result.put("classIds", values);
                } else if ("S".equals(type)) {
                    result.put("studentIds", values);
                }
            }
        }
        return result;
    }

    private void checkExcel(List<ExcelTeachingDto> excel, List<ErrorExcelVo> errorExcelVos) {

        long index = 1;

        for (ExcelTeachingDto excelTeachingClass : excel) {
            //存储当前行唯一标识
            excelTeachingClass.setIndex(index);
            index++;
        }

        excel.forEach(o -> {
            if (StringUtils.isBlank(o.getTeachingClassName())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行教学班名称不能为空");
                errorExcelVos.add(errorExcelVo);
            }


            if (StringUtils.isBlank(o.getCourseName())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行课程名称不能为空");
                errorExcelVos.add(errorExcelVo);
            }

            if (StringUtils.isBlank(o.getCourseName()) && ObjUtil.isNotNull(o.getType()) && o.getType().equals(0)) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行无需选课但对应行政班为空");
                errorExcelVos.add(errorExcelVo);
            }

            if (StringUtils.isBlank(o.getStudentObject()) && ObjUtil.isNotNull(o.getType()) && o.getType().equals(0)) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行无需选课但上课对象为空");
                errorExcelVos.add(errorExcelVo);
            }


            if (ObjUtil.isNull(o.getType())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行未设置是否需要选课");
                errorExcelVos.add(errorExcelVo);
            }

            if (StringUtils.isBlank(o.getCampusName())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行未设置校区");
                errorExcelVos.add(errorExcelVo);
            }


            if (ObjUtil.isNull(o.getFlag())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行未设置是课程还是环节");
                errorExcelVos.add(errorExcelVo);
            }


            if (ObjUtil.isNull(o.getHourType())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行授课类型为空");
                errorExcelVos.add(errorExcelVo);
            }


            if (StringUtils.isBlank(o.getLectureWeek())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行开课周为空");
                errorExcelVos.add(errorExcelVo);
            }

            if (ObjUtil.isNotNull(o.getFlag()) && o.getFlag().equals(1) && ObjUtil.isNull(o.getLectureWeekNum())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行是课程但未设置周学时");
                errorExcelVos.add(errorExcelVo);
            }


            if (ObjUtil.isNotNull(o.getFlag()) && o.getFlag().equals(1) && ObjUtil.isNull(o.getLectureConnectSection())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行是课程但未设置连上节次");
                errorExcelVos.add(errorExcelVo);
            }

            if (ObjUtil.isNotNull(o.getFlag()) && o.getFlag().equals(1) && ObjUtil.isNull(o.getLectureConnectNumber())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行是课程但未设置连上次数");
                errorExcelVos.add(errorExcelVo);
            }


            if (ObjUtil.isNull(o.getLectureRoomType())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行场地类型为空");
                errorExcelVos.add(errorExcelVo);
            }

            if (StringUtils.isBlank(o.getLectureTeacherNo())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(o.getIndex());
                errorExcelVo.setErrorMsg("第" + o.getIndex() + "行教师工号为空");
                errorExcelVos.add(errorExcelVo);
            }


            if (ObjUtil.isNotNull(o.getLectureConnectSection()) && ObjUtil.isNotNull(o.getLectureConnectNumber()) && ObjUtil.isNotNull(o.getLectureWeekNum())) {
                if (o.getLectureWeekNum() < o.getLectureConnectSection() * o.getLectureConnectNumber()) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(o.getIndex());
                    errorExcelVo.setErrorMsg("第" + o.getIndex() + "行周学时小于连上节次和连上次数的成绩");
                    errorExcelVos.add(errorExcelVo);
                }

            }
        });


    }

    private List<ExcelTeachingDto> readTeachingClassToExcel(MultipartFile file) {
        List<ExcelTeachingDto> excelTeachingClassDtos = new ArrayList<>();

        List<String> expectedHeaders = Arrays.asList(
                "教学班名称", "课程名称", "对应行政班名称", "教学班上课对象", "年级名称", "是否需要选课", "校区名称", "课程/环节标识", "授课类型",
                "开课周", "周学时", "连上节次", "连上次数", "场地类型", "上课场地", "教师工号");
        try {
            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("教学班名称", "teachingClassName");
            reader.addHeaderAlias("课程名称", "courseName");
            reader.addHeaderAlias("对应行政班名称", "classNames");
            reader.addHeaderAlias("教学班上课对象", "studentObject");
            reader.addHeaderAlias("年级名称", "gradeName");
            reader.addHeaderAlias("是否需要选课", "type");
            reader.addHeaderAlias("校区名称", "campusName");
            reader.addHeaderAlias("课程/环节标识", "flag");
            reader.addHeaderAlias("授课类型", "hourType");

            reader.addHeaderAlias("开课周", "lectureWeek");
            reader.addHeaderAlias("周学时", "lectureWeekNum");
            reader.addHeaderAlias("连上节次", "lectureConnectSection");
            reader.addHeaderAlias("连上次数", "lectureConnectNumber");
            reader.addHeaderAlias("场地类型", "lectureRoomType");
            reader.addHeaderAlias("上课场地", "lectureRoomName");
            reader.addHeaderAlias("教师工号", "lectureTeacherNo");

            excelTeachingClassDtos = reader.read(1, 2, ExcelTeachingDto.class);
            reader.close();
        } catch (IOException e) {
            log.info("excel导入教学任务失败:{}", e.getMessage());
        }
        if (excelTeachingClassDtos.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }
        return excelTeachingClassDtos;


    }

    @Override
    public Boolean checkSubClass(Integer taskId, String gradeId, Long courseId) {
        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId, taskId).eq(TeachingClass::getGradeId, gradeId).eq(TeachingClass::getCourseId, courseId)
                .eq(TeachingClass::getFlag, 1).isNotNull(TeachingClass::getUniqueShiftSign)
                .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        return CollUtil.isNotEmpty(teachingClassList);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deletedHourTypeByTeachingClassIds(Integer taskId, HourTypeDto hourTypeDto) {


        //根据获取的teachingClasses获取对应的teachingClassid
        List<Long> teachingIds = hourTypeDto.getTeachingClassIds();


        //根据获取的teachingIds获取对于的teachingClassWeek
        if (CollUtil.isNotEmpty(teachingIds)) {
            teachingClassWeekMapper.delete(new LambdaQueryWrapper<TeachingClassWeek>()
                    .in(TeachingClassWeek::getTeachingClassId, teachingIds)
                    .eq(TeachingClassWeek::getHourType, hourTypeDto.getHourType())
                    .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));


            teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>()
                    .in(TeachingClassTeacher::getTeachingClassId, teachingIds)
                    .eq(TeachingClassTeacher::getTeacherType, hourTypeDto.getHourType())
                    .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));
        }

        if (CollUtil.isNotEmpty(teachingIds)) {
            //获取未被删除的teachingClassweek
            List<TeachingClassWeek> teachingClassWeekList = teachingClassWeekMapper.selectList(new LambdaQueryWrapper<TeachingClassWeek>()
                    .in(TeachingClassWeek::getTeachingClassId, teachingIds).eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));

            List<Long> deleteTeachingClassIds = new ArrayList<>();
            teachingIds.forEach(o -> {
                List<TeachingClassWeek> teachingClassWeeks = teachingClassWeekList.stream().filter(p -> p.getTeachingClassId().equals(o)).collect(Collectors.toList());

                if (CollUtil.isEmpty(teachingClassWeeks)) {
                    deleteTeachingClassIds.add(o);
                }
            });

            //删除没有teachingClassWeek的教学班
            if (CollUtil.isNotEmpty(deleteTeachingClassIds)) {

                teachingClassMapper.delete(new LambdaQueryWrapper<TeachingClass>()
                        .in(TeachingClass::getTeachingClassId, deleteTeachingClassIds)
                        .eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

                teachingClassTeacherMapper.delete(new LambdaQueryWrapper<TeachingClassTeacher>()
                        .in(TeachingClassTeacher::getTeachingClassId, deleteTeachingClassIds)
                        .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));


                teachingClassWeekMapper.delete(new LambdaQueryWrapper<TeachingClassWeek>()
                        .in(TeachingClassWeek::getTeachingClassId, deleteTeachingClassIds)
                        .eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()));


                teachingClassStudentMapper.delete(new LambdaQueryWrapper<TeachingClassStudent>()
                        .in(TeachingClassStudent::getTeachingClassId, deleteTeachingClassIds)
                        .eq(TeachingClassStudent::getDeleted, Deleted.NOT.getCode()));
            }

        }


        return "删除成功";
    }

    @Override
    public String addHourTypeByTeachingClassIds(Integer taskId, HourTypeDto hourTypeDto) {


        List<TeachingClassWeek> teachingClassWeekList = new ArrayList<>();
        List<TeachingClassTeacher> teachingClassTeacherList1 = new ArrayList<>();

        List<Long> teachingClassIds = hourTypeDto.getTeachingClassIds();
        //根据获取的teachingIds获取对于的teachingClassWeek
        if (CollUtil.isNotEmpty(hourTypeDto.getTeachingClassIds())) {
            List<TeachingClassTeacher> teachingClassTeacherList = teachingClassTeacherMapper.selectList(new LambdaQueryWrapper<TeachingClassTeacher>().in(TeachingClassTeacher::getTeachingClassId, teachingClassIds)
                    .eq(TeachingClassTeacher::getTeacherType, 1)
                    .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode()));


            for (Long teachingId : teachingClassIds) {
                TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                teachingClassWeek.setTeachingClassId(teachingId);
                teachingClassWeek.setWeek(hourTypeDto.getWeek());
                teachingClassWeek.setHourType(hourTypeDto.getHourType());
                teachingClassWeek.setRoomId(hourTypeDto.getRoomId());
                teachingClassWeek.setRoomType(hourTypeDto.getRoomType());
                teachingClassWeek.setWeekNum(hourTypeDto.getWeekNum());
                teachingClassWeek.setSign(hourTypeDto.getSign());
                teachingClassWeek.setStartWeek(hourTypeDto.getStartWeek());
                teachingClassWeek.setEndWeek(hourTypeDto.getEndWeek());
                teachingClassWeek.setConnectNumber(hourTypeDto.getConnectNumber());
                teachingClassWeek.setConnectSection(hourTypeDto.getConnectSection());
                teachingClassWeek.setAssessmentId(hourTypeDto.getAssessmentId());
                teachingClassWeek.setAssessmentName(hourTypeDto.getAssessmentName());
                teachingClassWeek.setDeleted(Deleted.NOT.getCode());
                teachingClassWeekList.add(teachingClassWeek);


                List<TeachingClassTeacher> teachingClassTeachers = teachingClassTeacherList.stream().filter(p -> p.getTeachingClassId().equals(teachingId)).collect(Collectors.toList());

                if (CollUtil.isNotEmpty(teachingClassTeachers)) {
                    teachingClassTeachers.forEach(o -> {
                        TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                        teachingClassTeacher.setTeachingClassId(teachingId);
                        teachingClassTeacher.setTeacherId(o.getTeacherId());
                        teachingClassTeacher.setTeacherName(o.getTeacherName());
                        teachingClassTeacher.setTeacherType(hourTypeDto.getHourType());
                        teachingClassTeacherList1.add(teachingClassTeacher);
                    });
                }
            }
        }

        teachingClassWeekService.saveBatch(teachingClassWeekList);

        teachingClassTeacherService.saveBatch(teachingClassTeacherList1);


        return "添加成功";
    }

    @Override
    public Integer oddEvenWeekStatistics(Integer taskId) {

        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>().eq(TeachingClass::getTaskId, taskId).eq(TeachingClass::getDeleted, Deleted.NOT.getCode()));

        List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());

        if (CollUtil.isNotEmpty(teachingClassIds)) {

            List<TeachingClassWeek> list = teachingClassWeekService.lambdaQuery().in(TeachingClassWeek::getTeachingClassId, teachingClassIds).eq(TeachingClassWeek::getDeleted, Deleted.NOT.getCode()).list();

            long singleCount = list.stream().filter(p -> p.getSign().equals(1)).count();
            long doubleCount = list.stream().filter(p -> p.getSign().equals(2)).count();

            if (singleCount >= doubleCount) {
                return 2;
            } else {
                return 1;
            }
        }

        return 0;
    }

    @Override
    public String allTeachingClassToExcel(Integer taskId) {
        String modelPath = GlobalConstant.MODEL_EXCEL_PATH + "【模板】教学班信息.xls";
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        String storePath = "/" + taskInfo.getTaskName() + "/syncTeachingClass.xlsx";
        String targetPath = GlobalConstant.OUTPUT_EXCEL_PATH + storePath;

        FileUtil.copy(modelPath, targetPath, true);
        ExcelWriter writer = ExcelUtil.getWriter(targetPath);
        writer.setSheet(0);
        writer.passCurrentRow();
        writer.passCurrentRow();
        String httpPath = GlobalConstant.ACCESS_PATH + "/static/OutputExcel" + storePath;

        //课程教学班
        List<SyncTeachingClassDto> courseTeachingClassList = teachingClassMapper.syncCourseTeachingClassDto(taskId);
        //环节教学班
        List<SyncTeachingClassDto> segmentTeachingClassList = teachingClassMapper.syncSegmentTeachingClassDto(taskId);
        courseTeachingClassList.addAll(segmentTeachingClassList);
        if (CollUtil.isEmpty(courseTeachingClassList)) {
            writer.close();
            return httpPath;
        }
        List<Long> teachingClassIds = courseTeachingClassList.stream().map(SyncTeachingClassDto::getTeachingClassId).collect(Collectors.toList());
        //获取行政班 及对应年级
        Map<Long, ClassInfo> classMap = classInfoMapper.selectList(
                new LambdaQueryWrapper<ClassInfo>()
                        .eq(ClassInfo::getTaskId, taskId))
                .stream().collect(Collectors.toMap(ClassInfo::getId, a -> a));
        //教学班学生
        Map<Long, List<ExcelStudent>> studentMap = studentMapper.getExcelStudent(teachingClassIds)
                .stream().collect(Collectors.groupingBy(ExcelStudent::getTeachingClassId));
        //获取教师信息
        Map<Long, List<Teacher>> teachingClassToTeacher = teacherService.getTeacherByTeachingClassIds(teachingClassIds).stream()
                .collect(Collectors.groupingBy(Teacher::getTeachingClassId));
        //年级对应年级统一标识
        Map<String, String> globalGradeMap = yunService.getGrade(taskInfo.getSchoolId())
                .stream().collect(Collectors.toMap(BaseGrade::getGradeID, BaseGrade::getGlobalGrade));

        List<List<String>> rows = new ArrayList<>();
        for (SyncTeachingClassDto teachingClass : courseTeachingClassList) {
            String courseName = "";
            String teachingClassName = "";
            //暂且只有一个老师
            String teacherId = "";
            //上课对象字符串 C|2021级英语2班,2021级英语3班;S|stu036,stu037. 去掉已存行政班的学生
            String students = "";
            String globalGrade = globalGradeMap.size() > 0 ? new ArrayList<>(globalGradeMap.values()).get(0) : "U1";
            globalGrade = StrUtil.isBlank(teachingClass.getGradeId()) ? globalGrade : globalGradeMap.getOrDefault(teachingClass.getGradeId(), globalGrade);
            //teachingClass.getUniqueShiftSign() 不为null表示是拆班数据。学生传的是学生字符串
            //teachingClass.getTeachingClassType() == 1  0不是选课  1选课教学班
            if (StrUtil.isNotBlank(teachingClass.getUniqueShiftSign())
                    || teachingClass.getTeachingClassType() == 1) {

                courseName = teachingClass.getCourseName();
                teachingClassName = teachingClass.getTeachingClassName();
                if (teachingClassToTeacher.containsKey(teachingClass.getTeachingClassId())) {
//                    teacherId = teachingClassToTeacher.get(teachingClass.getTeachingClassId()).get(0).getBaseTeacherId();
                    //多教师版本
                    teacherId = teachingClassToTeacher.getOrDefault(teachingClass.getTeachingClassId(), new ArrayList<>()).stream()
                            .map(Teacher::getBaseTeacherId).distinct().collect(Collectors.joining(","));
                }
                //学生字符串
                students = studentMap.getOrDefault(teachingClass.getTeachingClassId(), new ArrayList<>()).stream()
                        .map(ExcelStudent::getBaseStudentId).collect(Collectors.joining(","));
                if (StrUtil.isNotBlank(students)) {
                    students = "S|" + students;
                }
                List<String> row = CollUtil.newArrayList(courseName, teachingClassName, teacherId, "覆盖", students, globalGrade);
                rows.add(row);
            } else {
                courseName = teachingClass.getCourseName();
                teachingClassName = teachingClass.getTeachingClassName();
                if (teachingClassToTeacher.containsKey(teachingClass.getTeachingClassId())) {
//                    teacherId = teachingClassToTeacher.get(teachingClass.getTeachingClassId()).get(0).getBaseTeacherId();
                    //多教师版本
                    teacherId = teachingClassToTeacher.getOrDefault(teachingClass.getTeachingClassId(), new ArrayList<>()).stream()
                            .map(Teacher::getBaseTeacherId).distinct().collect(Collectors.joining(","));

                }
                //学生字符串
                students = studentMap.getOrDefault(teachingClass.getTeachingClassId(), new ArrayList<>()).stream()
                        .map(ExcelStudent::getBaseStudentId).collect(Collectors.joining(","));
                if (StrUtil.isNotBlank(students)) {
                    students = "S|" + students;
                }
                //行政班下有多个专业的学生  学生教学计划不一样
//                if (StrUtil.isNotBlank(teachingClass.getToClass()) && StrUtil.isNotBlank(students)) {
//                    students = students + ";";
//                }
//                if (StrUtil.isNotBlank(teachingClass.getToClass())) {
//                    //行政班id转化为行政班名称
//                    String[] classIds = teachingClass.getToClass().split(",");
//                    String className = Arrays.stream(classIds).map(a -> classMap.get(Long.valueOf(a)).getClassName()).collect(Collectors.joining(","));
//                    students = students + "C|" + className;
//                }
                List<String> row = CollUtil.newArrayList(courseName, teachingClassName, teacherId, "覆盖", students, globalGrade);
                rows.add(row);
            }
        }
        writer.write(rows, false);
        writer.close();
        return httpPath;
    }


}